It's fairly straight-forward, but there are gotchas:
- If
.allCheck
is changed by the user, drive the .checks
checkboxes from it
- If a
.checks
checkbox is changed by the user, drive the .allCheck
checkbox based on whether all or none of .checks
are (now) checked
// If `.allCheck` is changed by the user, drive the `.checks` checkboxes from it
$(".allCheck").on("change", function() {
$(".checks").prop("checked", this.checked);
});
// If a `.checks` checkbox is changed by the user, drive the `.allCheck`
// checkbox based on whether all or none of `.checks` are (now) checked
$(".checks").on("change", function() {
var all = $(".checks").get().every(function(cb) {
return cb.checked;
});
$(".allCheck").prop("checked", all);
});
<label><input type="checkbox" class="allCheck" />all</label>
<label><input type="checkbox" class="checks" />shoes</label>
<label><input type="checkbox" class="checks" />bag</label>
<label><input type="checkbox" class="checks" />car</label>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Note in the above I have not done this
...and disabled
We can, but it's not the way these things are usually most useful. Instead, the above makes it easy to pick all but one (by ticking "all," then unticking the one).
But if you really want that disabled behavior, granted it's a bit simpler: You flag disabled
via .prop("disabled", flag)
and only have to handle changes to .allCheck
.
$(".allCheck").on("change", function() {
$(".checks")
.prop("checked", this.checked)
.prop("disabled", this.checked)
});
<label><input type="checkbox" class="allCheck" />all</label>
<label><input type="checkbox" class="checks" />shoes</label>
<label><input type="checkbox" class="checks" />bag</label>
<label><input type="checkbox" class="checks" />car</label>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>