Skip to content Skip to sidebar Skip to footer

How To Disable Enable A Checkbox Based On Another Checkbox?

Following code is generated by a for loop.
).change(function() { //When checkbox changesvar checked = $(this).attr("checked"); $(this).next().attr("disabled", !checked); //The next checkbox will enable });​ // or disable based on the// checkbox before it

Demo:http://jsfiddle.net/DerekL/Zdf9d/Pure JavaScript:http://jsfiddle.net/DerekL/Zdf9d/1/

Update

It will uncheck the first checkboxes when the Special checkbox is checked. Pure JavaScript:http://jsfiddle.net/DerekL/Zdf9d/2/

More Updates

Here's the demo: Pure JavaScript:http://jsfiddle.net/DerekL/Zdf9d/3/jQuery:http://jsfiddle.net/DerekL/Zdf9d/4/

Little note: document.querySelectorAll works on all modern browsers and IE8+ including IE8. It is always better to use jQuery if you want to support IE6.

Solution 2:

You can't use yes[] as an identifier in the Javascript, so you have to access the field using the name as a string:

document.mainForm["yes[]"]

This will not return a single element, it will return an array of elements. Use an index to access a specific element:

document.mainForm["yes[]"][0]

The value of the checkbox will always be the value property, regardless of whether the checkbox is selected or not. Use the checked property to find out if it's selected:

functionspenable() {
  var yes = document.mainForm["yes[]"][0].checked;
  if (yes) {
    alert("true");
  } else {
    alert("false");
  };
}

To access the specific checkbox that was clicked, send the index of the checkbox in the event call:

<inputclass="cbox_yes"type="checkbox" name="yes[]" value="01.jpg" onclick="spenable(0);" /> OK

Use the index in the function:

functionspenable(idx) {
  var yes = document.mainForm["yes[]"][idx].checked;
  var sp = document.mainForm["sp[]"][idx];
  sp.disabled = !yes;
}

Solution 3:

If you are open to using jQuery:

$('input[type="checkbox"]').click(function(){
    var obj = $(this);
    obj.next('.cbox_sp').attr({'disabled':(obj.is(':checked') ? false : 'disabled')});
});

This solution will assign an onclick event handler to all checkboxes and then check to see if the corresponding "special" checkbox should be disabled or not. It also sets the default checked state to true.

Working Example: http://jsfiddle.net/6YTqC/

Post a Comment for "How To Disable Enable A Checkbox Based On Another Checkbox?"