我有多个具有相同类名的表。我需要每个表在每个表中都有一个check-all / uncheck all复选框,并检查/取消选中其自己表中的所有其他复选框。
我在这里发现其他代码似乎可行;但是,当试图将其插入我的场景时,它根本不起作用。我希望能够使用与我的jquery示例中的代码一样干净的代码;但是,如果代码需要更改为另一个代码以使其工作,请随时向我显示其他代码。我愿意接受选择,只是想确保我以最好的方式做到这一点。这是一个项目;但是,我希望学习如何做到这一点,以便我可以在未来的项目中继续使用它。
我很感激所有帮助,因为我对javascript / jquery很新。
Jquery的
$('#chkSelectAll').click(function() {
if ($(this).is(':checked')) {
$('.permissions > input[type=checkbox]').each(function() {
$(this).prop("checked", true);
});
}
else {
$('.permissions input[type=checkbox]').each(function() {
$(this).prop("checked", false); $('#sel').text('Select All');
});
}
});
HTML
<table id="table1" class="permissions">
<tr class="SLheader"><td><b>TABLE 1</b></td><td><input type="checkbox" id="chkSelectAll" /></td></tr>
<tr class="second"><td>First Row</td><td><input type="checkbox" name="first"></td></tr>
<tr><td>Second Row</td><td><input type="checkbox" name="second"></td></tr>
<tr class="second"><td>Third Row</td><td><input type="checkbox" name="third"></td></tr>
</table>
<br />
<table id="table1" class="permissions">
<tr class="SLheader"><td><b>TABLE 2</b></td><td><input type="checkbox" id="chkSelectAll" /></td></tr>
<tr class="second"><td>First Row</td><td><input type="checkbox" name="first"></td></tr>
<tr><td>Second Row</td><td><input type="checkbox" name="second"></td></tr>
<tr class="second"><td>Third Row</td><td><input type="checkbox" name="third"></td></tr>
</table>
<br />
<table id="table1" class="permissions">
<tr class="SLheader"><td><b>TABLE 3</b></td><td><input type="checkbox" id="chkSelectAll" /></td></tr>
<tr class="second"><td>First Row</td><td><input type="checkbox" name="first"></td></tr>
<tr><td>Second Row</td><td><input type="checkbox" name="second"></td></tr>
<tr class="second"><td>Third Row</td><td><input type="checkbox" name="third"></td></tr>
</table>
JSFiddle:http://jsfiddle.net/sfu7h8wf/
这个jquery代码根本不起作用。我试图确保改变以确定它是否有效;但是,我在这里用它作为一个例子来解释我在寻找什么。
答案 0 :(得分:0)
修正ID问题,请尝试:
$('.chkSelectAll').click(function () {
$(this).closest('table').find('input[type="checkbox"]:gt(0)').prop('checked', $(this).prop('checked'))
});
$('.permissions').find('input[type="checkbox"]:gt(0)').change(function () {
var totalSibs = $(this).closest('table').find('input[type="checkbox"]:gt(0)').length;
var checkedSibs = $(this).closest('table').find('input[type="checkbox"]:gt(0):checked').length;
if (checkedSibs === 0) {
$(this).closest('table').find('input[type="checkbox"]:first').prop('checked', false);
$(this).closest('table').find('input[type="checkbox"]:first').prop('indeterminate', false);
} else if (checkedSibs === totalSibs) {
$(this).closest('table').find('input[type="checkbox"]:first').prop('checked', true);
$(this).closest('table').find('input[type="checkbox"]:first').prop('indeterminate', false);
} else {
$(this).closest('table').find('input[type="checkbox"]:first').prop('indeterminate', true)
}
})
<强> jsFiddle example 强>