-1

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?

4
  • You can check for javascript syntax errors with : jslint.com. It has a slight learning curve but its extremely useful. Commented Mar 25, 2011 at 0:55
  • @havok, how is that useful in this particular case? Commented Mar 25, 2011 at 0:56
  • Consider using radio buttons instead of checkboxes. The user is likely to be less confused by radio buttons behaving normally than by checkboxes behaving like radio buttons. Commented Mar 25, 2011 at 1:06
  • @J-P, part of his question was whether his syntax is correct. jslint can confirm that it is. It doesn't answer his question so thats why I only put it as a comment. Commented Mar 25, 2011 at 1:58

4 Answers 4

2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

You need to remove extra closing brackets after functions. Here is a working example uses jquery: jsfiddle.net/billymoon/wAukf
0

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.

Comments

0

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"

Comments

0

Try:

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

So:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.