Max06270 Max06270 - 3 months ago 8
jQuery Question

Jquery Unselect all Checkbox Multiple Forms

I am trying to build filters for the users including a select/unselect all functionality.

I have founded plenty of correct examples but none of them has more than one filter on the demos, and right now it is behaving strangely.

When I click on (All) for filter1 it'is working fine but not the (All) for filter2...

JSFIDDLE:

https://jsfiddle.net/Max06270/pvtqpn8a/#&togetherjs=2tvV3Mhb7l

HTML:

<div id="filter1">
<form action='#'>
<input type="checkbox" id="select-all" checked>(All)<br>
<!-- Should select/unselect only the F1 checkboxes -->
<input type="checkbox" id="checkbox-f1" checked>F1: Value1<br>
<input type="checkbox" id="checkbox-f1" checked>F1: Value2<br>
<input type="checkbox" id="checkbox-f1" checked>F1: Value3<br>
<input type="checkbox" id="checkbox-f1" checked>F1: Value4<br>
<input type="submit" id="submit-f1" value="Apply">
</form>
</div>
<br>
<div id="filter2">
<form action='#'>
<input type="checkbox" id="select-all" checked>(All)<br>
<!-- Should select/unselect only the F2 checkboxes -->
<input type="checkbox" id="checkbox-f2" checked>F2: Value1<br>
<input type="checkbox" id="checkbox-f2" checked>F2: Value2<br>
<input type="checkbox" id="checkbox-f2" checked>F2: Value3<br>
<input type="checkbox" id="checkbox-f2" checked>F2: Value4<br>
<input type="submit" id="submit-f2" value="Apply">
</form>
</div>


JS:

$("#select-all").change(function () {
$(this).siblings().prop('checked', $(':checkbox').prop("checked"));
});


Thank you in advance,
Max

Answer

You should not keep the same id. for both (All) checkboxes. Change id to class and use below code.

$(".select-all").change(function () {
    $(this).siblings().prop('checked', $(this).prop("checked"));
});

You were always checking the prop for first checkbox. Actually you need to check the property of clicked checkbox only.