yosafat yosafat - 1 month ago 5
HTML Question

Jquery - how to make checkall is unchecked when one of checkbox uncheck?

i have a code like this :

$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});


this code it's work, if i click checkbox
#checkall
, it's check all
checkbox
, if i uncheck
#checkall
, it's uncheck all
checkbox
.

The first problem is if i check
#checkall
, it's check all
checkbox
, but when i uncheck one of
checkbox
that's
#checkall
still checked, actually it's not checked because one of
checkbox
is unchecked and automatically not checked all.

Second is if i manually check all one by one
checkbox
, the
#checkall
not checked, actually the checked is checked all.

how to solve this?

Answer

Add an event handler to the other checkboxes that simply tests whether all of them are checked or not:

var checkAll = $("#checkAll").click(function () {
  allCBs.prop('checked', this.checked);
});

var allCBs = $("input:checkbox:not(#checkAll)").click(function() {
  checkAll.prop("checked", !allCBs.is(":not(:checked)"));
});
label { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<label><input type="checkbox" id="checkAll"> Check All</label>
<label><input type="checkbox"> ABC</label>
<label><input type="checkbox"> DEF</label>
<label><input type="checkbox"> GHI</label>

Note: I prefer to use the click event rather than the change event, because some (older IE) browsers don't trigger a change until focus leaves the field.

Comments