我有一个脚本,可以将子复选框分组到父复选框下。它运行良好,除了如果取消选中任何子复选框,我希望取消选中父复选框。如果选中了所有子框,则还应选中父复选框。我将如何实现这一目标?
.HTML:
<form>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Africa
<div class="content">
<input type="checkbox" value="" name="countries" class="childCheckBox" /> Algeria<br />
<input type="checkbox" value="" name="countries" class="childCheckBox" /> Angola<br />
</div>
</fieldset>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> North America
<div class="content">
<input type="checkbox" value="" name="countries" class="childCheckBox" /> Canada<br />
<input type="checkbox" value="" name="countries" class="childCheckBox" /> United States<br />
</div>
</fieldset>
</form>
Javascript:
$(document).ready(
function() {
//clicking the parent checkbox should check or uncheck all child checkboxes
$(".parentCheckBox").click(
function() {
$(this).parents('fieldset:eq(0)').find('.childCheckBox').prop('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);
}
}
);
}
);
小提琴:http://jsfiddle.net/TRTMS/4/
将childCheckBox
的length
与:checked
的length
进行比较:
$('input.parentCheckBox').prop('checked', $('input.childCheckBox').length === $('input.childCheckBox:checked').length);