使用 jQuery 切换(启用/禁用)HTML 表中的所有复选框

Toggle (enable / disable) all checkboxes in an HTML table with jQuery

本文关键字:复选框 HTML 切换 jQuery 启用 禁用 使用      更新时间:2023-09-26

我想在HTML <table>中添加一个Enable all复选框,以切换该<table>内的所有复选框。

我无法让它工作。

我的查询 :

var elementName = 'TestName';
$('input[familyname="TestName"]').on('click', function() {
    if ($("input[familyname='" + elementName + "']").is(':checked')) {
        $(this).find('tr').nextAll('tr').find('input').prop('checked', true);
    } else {
        $(this).find('tr').nextAll('tr').find('input').prop('checked', false);
    }
});

另请参阅此小提琴。

<小时 />

更新:

我让它使用以下代码:

var elementName = 'TestName';
var $checkboxes = $('.table-list').find('input'); 
$('input[familyname="TestName"]').on('click', function() {
    $checkboxes.prop('checked', $(this).is(':checked'));
});

但是,当我想添加更多表时存在错误。看到这个小提琴。

你必须像下面这样更改你的代码,

var elementName = 'TestName';
$('input[familyname="' + elementName + '"]').on('click', function() {
  var elems = $(this).closest('table.table').find('tr input');
  elems.prop('checked', this.checked)
});

在我们的上下文中,tr是父母,因此.find() $(this)是行不通的。因此,我们必须使用 .closest() 来获取父表,从中我们可以获取所有必需的输入 - 复选框元素。

演示


您设置了两个单选按钮的相同 id,为单选按钮提供唯一 ID 并使用上面的代码。

演示

这是实现所需效果的简单但最佳的方法,适用于任意数量的复选框组:

var elementName = 'TestName';
$('input[familyname="' + elementName + '"]').on('click', function(e) {
    $(this)
        .closest('.table-list')
        .find('input')
        .prop('checked', this.checked);
});

(另见这首小提琴

如果你输入thead那么你不能直接做.find()而是遍历到tbody并选择所有type=checkbox input,比如:

 $(this).closest("table").find('tbody input[type=checkbox]').prop('checked', true);

同样,请执行以下操作:

 $(this).closest("table").find('tbody input[type=checkbox]').prop('checked', false);

试试这个:

$(document).on('click', '#switchall1', function() {
if ($(this).is(':checked')) {
    $(this).closest('table').find('tbody tr input').prop('checked', true);
}
else {
    $(this).closest('table').find('tbody tr input').prop('checked', false);
}

});