gpt4 book ai didi

javascript - 具有父级和子级选择的复选框

转载 作者:行者123 更新时间:2023-11-28 19:39:52 26 4
gpt4 key购买 nike

我有一排复选框,我想要以下内容:- 单击父项时选择/取消选择所有子项复选框- 当所有复选框都被选中(包括父复选框)并且您取消选中子复选框之一时,父复选框也应该取消选中。

我有这个代码:

$(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);
}
}
);
});

这是一个 fiddle :http://jsfiddle.net/2b2hw58d/1/

为什么不起作用?

最佳答案

您需要使用.prop()而不是.attr()另外,使用.closest()找到与选择器匹配的最接近的祖先元素。

jQuery(function ($) {
//clicking the parent checkbox should check or uncheck all child checkboxes
$(".parentCheckBox").click(function () {
$(this).closest('fieldset').find('.childCheckBox').prop('checked', this.checked);
});
//clicking the last unchecked or checked checkbox should check or uncheck the parent checkbox
$('.childCheckBox').click(function () {
var $fs = $(this).closest('fieldset');
$fs.find('.parentCheckBox').prop('checked', !$fs.find('.childCheckBox').is(':not(:checked)'))
});
});

演示:Fiddle

关于javascript - 具有父级和子级选择的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25300757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com