tags:

views:

266

answers:

2

I have a bunch of checkboxes like this. If the "Check Me" checkbox is checked, all the other 3 checkboxes should be enabled, else they should be disabled. How can I do this using Jquery?

<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9">Check Me
<input type="checkbox" name="chk9[120]">
<input type="checkbox" name="chk9[140]">
<input type="checkbox" name="chk9[150]">
</form>
+4  A: 

Change your markup slightly:

<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="group1">Check Me
<input type="checkbox" name="chk9[120]" class="group1">
<input type="checkbox" name="chk9[140]" class="group1">
<input type="checkbox" name="chk9[150]" class="group1">
</form>

and then

$(function() {
  enable_cb();
  $("#group1").click(enable_cb);
});

function enable_cb() {
  if (this.checked) {
    $("input.group1").removeAttr("disabled");
  } else {
    $("input.group1").attr("disabled", true);
  }
}

You can do this using attribute selectors without introducing the ID and classes but it's slower and (imho) harder to read.

cletus
For the disabling part, try this url: http://jquery-howto.blogspot.com/2008/12/how-to-disableenable-element-with.html
Walt Stoneburner
This is not directly related to the question, but in IE the change event will not fire until the checkbox loses focus. I usually call `$(this).change` on the click event of the first checkbox.
mcrumley
Woops, got it in my head to check/uncheck the checkboxes not to enable/disable them. Fixed. :)
cletus
A: 
<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="chkAll">Check Me
<input type="checkbox" name="chk9[120]" class="chkGroup">
<input type="checkbox" name="chk9[140]" class="chkGroup">
<input type="checkbox" name="chk9[150]" class="chkGroup">
</form>

$("#chkAll").click(function() {
   $(".chkGroup").attr("checked", this.checked);
});

With added functionality to ensure the check all checkbox gets checked/dechecked if all individual checkboxes are checked:

$(".chkGroup").click(function() {
  $("#chkAll")[0].checked = $(".chkGroup:checked").length == $(".chkGroup").length;
});
zincorp