[英]Uncheck group checkbox if at least one in group is unchecked w/jQuery
I have a groups of checkboxes, with one that can check/uncheck the entire group. 我有一组复选框,其中一个可以选中/取消选中整个复选框。 This functionality should only apply to checkboxed that are not disabled. 此功能应仅适用于未禁用的复选框。 When I used "main" checkbox to select all and then uncheck one of the checkboxes below, I should also uncheck the main one. 当我使用“主要”复选框选中所有复选框,然后取消选中下面的复选框之一时,我也应该取消选中主要复选框。 However, if I check the one below back, thus making all checked, the "main" should become checked again. 但是,如果我将下面的一项选中,从而全部选中,则“主”项应再次变为选中状态。
I think I'm over complicating this code: 我认为我已经使该代码复杂化了:
var checkboxes = $("#myTable input[type=checkbox:enabled]:not(:first)").change(function() {
var allIsChecked = checkboxes.length === checkboxes.filter(":checked").length;
all[0].checked = allIsChecked;
});
var all = $("#checkAll").change(function() {
checkboxes.attr("checked",this.checked);
});
Your selector [type=checkbox:enabled]
is not valid. 您的选择器[type=checkbox:enabled]
无效。 You can exclude the disabled radio buttons by adding a not($("#myTable input[disabled=disabled]"))
as such: 您可以通过添加not($("#myTable input[disabled=disabled]"))
来排除禁用的单选按钮,如下所示:
var $checkboxes =
$("#myTable input[type=checkbox]:not(:first)").
not($("#myTable input[disabled=disabled]")).
change(function() {
var allIsChecked = $checkboxes.length === $checkboxes.filter(":checked").length;
$all[0].checked = allIsChecked;
});
var $all = $("#checkAll").change(function() {
$checkboxes.attr("checked", this.checked);
});
You can test here . 你可以在这里测试。 Select all child radio buttons or select the main radio button 选择所有子单选按钮或选择主单选按钮
I think your code could be simpler : 我认为您的代码可能更简单:
var checkboxes = $("#myTable input[type=checkbox]:not(:first)");
checkboxes.change(function() {
var allIsChecked = checkboxes.filter(:enabled:not(:checked)).size() === 0;
all[0].checked = allIsChecked;
});
var all = $("#checkAll").change(function() {
checkboxes.filter(":enabled").attr("checked",this.checked);
});
This just checks that there is no checkbox that is both enabled and unchecked. 这仅检查没有启用和未选中的复选框。 I also include disabled checkboxes in the selector in order that the check all still works if you reenable one of them. 我还在选择器中包括了禁用的复选框,以便在重新启用其中一项后仍可以进行全部检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.