Reputation: 3640
I'm trying to display a list of checkboxes with a 'Select All' option for every item, and a 'Select All' item for each group.
I have the following markup:
<fieldset>
<label>
<input type="checkbox" class="checkall"><strong> All</strong>
</label>
<fieldset>
<label>
<input type="checkbox" name="checkedLocations" class="chkChild checkall" value="China" />
<strong> China</strong>
</label>
<label>
<input type="checkbox" name="checkedLocations" class="chkChild" value="Hong Kong" checked="checked" />
Hong Kong
</label>
</fieldset>
<fieldset>
<label>
<input type="checkbox" name="checkedLocations" class="chkChild checkall" value="Australia" />
<strong> Australia</strong>
</label>
<label>
<input type="checkbox" name="checkedLocations" class="chkChild" value="NSW" />
NSW
</label>
<label>
<input type="checkbox" name="checkedLocations" class="chkChild" value="VIC" />
VIC
</label>
</fieldset>
</fieldset>
which produces the following checkboxes:
All, China, Hong Kong, Australia, NSW, VIC
What I'm trying to do is to have a Select All checkbox that selects/deselects everything, and a checkbox next to each country (Australia and China in this example) that selects/deselects all the locations in that country.
I'm using the following code:
$(function () {
$('.checkall').on('click', function () {
$(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
});
$('.chkChild').on('click', function () {
$(this).closest('fieldset').find('.checkall').prop('checked', false);
});
});
And the 'Select All' works, however when I click on China or Australia, the checkbox doesn't work and the child items aren't selected/deselected.
Upvotes: 0
Views: 1288
Reputation: 388316
Because you have both classes on that element
$(function () {
$('.checkall').on('click', function () {
$(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
});
$('.chkChild').on('click', function () {
if (!$(this).is('.checkall')) {
$(this).closest('fieldset').find('.checkall').prop('checked', false);
}
});
});
Demo: Fiddle
Upvotes: 1