I have a jQuery script that has multiple checkbox groups. If the 'Parent' is selected, it should also select all the 'Child' boxes and if any 'Child' boxes are unselected, then the 'Parent' should also be unselected and only the selected 'Child' boxes left checked.
Here is a jsFiddle: http://jsfiddle.net/9NmE7/
The problem is that with jQuery 1.4.2 this used to work great, but since upgrading to 1.10.2 it still works, but only ONCE. Meaning, if you click on 'Parent 1', it works. Then you deselect 'Parent 1' and it also works, but if you then click 'Parent 1' to select it again, it doesn't work anymore.
What is wrong here?
Just in case, here is the HTML:
<form>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Parent 1<br />
<input type="checkbox" class="childCheckBox" /> Child 1-1<br />
<input type="checkbox" class="childCheckBox" /> Child 1-2<br />
<input type="checkbox" class="childCheckBox" /> Child 1-3<br />
<input type="checkbox" class="childCheckBox" /> Child 1-4<br />
<input type="checkbox" class="childCheckBox" /> Child 1-5<br />
</fieldset>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Parent 2<br />
<input type="checkbox" class="childCheckBox" /> Child 2-1<br />
<input type="checkbox" class="childCheckBox" /> Child 2-2<br />
<input type="checkbox" class="childCheckBox" /> Child 2-3<br />
<input type="checkbox" class="childCheckBox" /> Child 2-4<br />
<input type="checkbox" class="childCheckBox" /> Child 2-5<br />
</fieldset>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Parent 3<br />
<input type="checkbox" class="childCheckBox" /> Child 3-1<br />
<input type="checkbox" class="childCheckBox" /> Child 3-2<br />
<input type="checkbox" class="childCheckBox" /> Child 3-3<br />
<input type="checkbox" class="childCheckBox" /> Child 3-4<br />
<input type="checkbox" class="childCheckBox" /> Child 3-5<br />
</fieldset>
</form>
And the jQuery:
$(document).ready(
function() {
//clicking the parent checkbox should check or uncheck all child checkboxes
$(".parentCheckBox").click(
function() {
$(this).parents('fieldset:eq(0)').find('.childCheckBox').attr('checked', this.checked);
}
);
//clicking the last unchecked or checked checkbox should check or uncheck the parent checkbox
$('.childCheckBox').click(
function() {
if ($(this).parents('fieldset:eq(0)').find('.parentCheckBox').attr('checked') == true && this.checked == false)
$(this).parents('fieldset:eq(0)').find('.parentCheckBox').attr('checked', false);
if (this.checked == true) {
var flag = true;
$(this).parents('fieldset:eq(0)').find('.childCheckBox').each(
function() {
if (this.checked == false)
flag = false;
}
);
$(this).parents('fieldset:eq(0)').find('.parentCheckBox').attr('checked', flag);
}
}
);
}
);