【发布时间】:2014-08-14 13:49:12
【问题描述】:
我有一排复选框,我想要以下内容: - 单击父选择/取消选择所有子复选框时 - 当所有复选框都被选中(包括父复选框)并且您取消选中其中一个子复选框时,父复选框也应该取消选中。
我有这个代码:
$(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);
}
}
);
});
这里是一个小提琴:http://jsfiddle.net/2b2hw58d/1/
为什么它不起作用?
【问题讨论】:
-
使用
.prop('checked', this.checked) -
还有
.closest('fieldset')而不是.parents('fieldset:eq(0)')
标签: javascript jquery html checkbox