简体   繁体   中英

What is wrong with this JavaScript code?

I have two checkboxes name check1 and check2. I wanted for either one to be disabled if the other one was checked. This is what I did:

var male = document.getElementById("check1");
var female = document.getElementById("check2");

male.disabled = (female.checked == true) ? true : false;
female.disabled = (male.checked == true) ? true : false;

It does not work at all. Is the syntax correct. What did I do wrong?

You need the onchange event, and your code could be tidied up as well.

var male = document.getElementById("check1"),
    female = document.getElementById("check2");

male.onchange = function() {
    female.disabled = male.checked;
};

female.onchange = function() {
    male.disabled = female.checked;
};

jsFiddle .

Also, shouldn't you be using radio input?

disabled shouldn't be set at all in order to be disabled AFAIK, any value is "truthy"

do .removeAttribute('disabled') to not have it disabled.

you need to change the state of the other checkbox when one is clicked eg. male changed - alter female, and versa verse.

function maleOnClick(){
    female.checked= !this.checked;
}
function femaleOnClick(){
    male.checked= !this.checked;
}

Anyway why dont you use type="radio"

Try:

 male.setAttribute('disabled', 'disabled'); //set
 male.setAttribute('disabled', ''); //clear

So:

male.setAttribute = (female.checked == true) ? 'disabled': '';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM