INTRODUCTION
I am trying to get a bunch of checkboxes checked or unchecked if I click on a "parent" checkbox.
1[]
2[][][][][][]
Something like: parent (1) gets checked; all child checkboxes (2) get checked. Parent gets unchecked, all child checkboxes get unchecked.
It works at html level: I can see how the checked property appears and disappears in the ELEMENTS tab in the developer tools on Microsoft Edge.
It works also in the UI, after loading the page, if I click on the parent checkbox all the children change accordingly. But that stops working when I click on any child. Then, even I can see how the element properties change as before, the change can't be seen graphically.
I am using jquery-3.6.0.
It looks like with older versions it works correctly.
JSFIDDLE DEMO OF THE PROBLEM
You can see the exact issue here:
Edit fiddle - JSFiddle - Code Playground[
^]
With jQuery 1.4.3 it works, with newer versions i.e. 3.4.1 it doesn't.
HOW TO TEST IT:
1. check the checkbox on top. All checkboxes will be checked.
2. check it again. All checkboxes will be unchecked.
3. check any of the checkboxes on the bottom line twice. All checkboxes will be unchecked.
4. check the checkbox on top again. All checkboxes except the one you checked in the step 3 will be checked.
My code:
<script src="./scripts/jquery-3.6.0.min.js"></script>
<script>
$(function() {
var childrenTemps = $("input:checkbox.cbTempsChild")
$("#cbTempsParent").change(function(){
if (this.checked) {
childrenTemps.attr("checked", "checked");
}
else {
childrenTemps.removeAttr("checked");
}
});
childrenTemps.change(function(){
var totalElements = childrenTemps.length;
var checkedElements = childrenTemps.filter(":checked").length;
if (totalElements === checkedElements) {
$("#cbTempsParent").attr("checked", "checked");
}
else {
$("#cbTempsParent").removeAttr("checked");
}
});
});
</script>
Any idea why this happens?
Thank you in advance for your time and help.
What I have tried:
All I have been able to think about, but mostly I am surprised to see this.