jeudi 18 août 2016

Auto check/uncheck the "All" checkbox

I am new to JS and I have a page with 2 filters, I am stuck and I am trying to:

  1. check automatically the (All) checkbox if every other checkbox of the filter are checked.

  2. when a user unchecked a checkbox, automatically uncheck the (All) checkbox.

I am trying the following code but it is not really working...

HTML:

<div id="filter1">
<form action='#'>
<input type="checkbox" value="all" class="select-all" checked>(All)
<br>
<input type="checkbox" value="v1" class="checkboxlistitem" checked>F1: Value1
<br>
<input type="checkbox" value="v2" class="checkboxlistitem" checked>F1: Value2
<br>
<input type="checkbox" value="v3" class="checkboxlistitem" checked>F1: Value3
<br>
<input type="checkbox" value="v4" class="checkboxlistitem" checked>F1: Value4
<br>
<input type="submit" value="Apply">
</form>
</div>

<div id="filter2">
<form action='#'>
<input type="checkbox" value="all" class="select-all" checked>(All)
<br>
<input type="checkbox" value="v1" class="checkboxlistitem" checked>F2: Value1
<br>
<input type="checkbox" value="v2" class="checkboxlistitem" checked>F2: Value2
<br>
<input type="checkbox" value="v3" class="checkboxlistitem" checked>F2: Value3
<br>
<input type="checkbox" value="v4" class="checkboxlistitem" checked>F2: Value4
<br>
<input type="submit" value="Apply">
</form>
</div>

JS:

$(".checkboxlistitem").change(function() {
$(".select-all").prop("checked", $(".checkboxlistitem:checked").length ==    $(".checkboxlistitem").length);});

JSFIDDLE:

http://ift.tt/2bFCTt3

Let me know if you need clarifications, Thanks in advance, Max




Aucun commentaire:

Enregistrer un commentaire