jQuery - 切换选择所有复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9669005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - toggle select all checkboxes
提问by user82302124
Fought with a bunch of examples and, being still new to jQuery/Javascript, cannot get my code to function (here my my template in gsp):
与一堆示例进行了斗争,并且仍然是 jQuery/Javascript 的新手,无法使我的代码运行(这里是我的 gsp 模板):
<table>
<thead>
<tr>
<th><input type="checkbox" name="selectAll" onclick="selectAll(this.checked);"/></th>
</tr>
</thead>
<tbody>
<td>
<td><input type="checkbox" name="domainList" value="${domainInstance.id}"/></td>
</tbody>
<table>
I have the following javascript snippet in my main gsp, that calls the template:
我的主 gsp 中有以下 javascript 片段,它调用模板:
function selectAll(status) {
}
How do I select all checkboxes from the selectAll name?
如何从 selectAll 名称中选择所有复选框?
回答by Selvakumar Arumugam
Since you are using jQuery, you should use an onclick
handler like below for selectAll.
由于您使用的是 jQuery,您应该onclick
对 selectAll使用如下所示的处理程序。
$(':checkbox[name=selectAll]').click (function () {
$(':checkbox[name=domainList]').prop('checked', this.checked);
});
Please note that the above code is going to look into the entire dom for the checkbox with name=selectAll
and set the status of the checkbox with name=domainList
.
请注意,上面的代码将查看复选框的整个 domname=selectAll
并使用 设置复选框的状态name=domainList
。
Below is a slightly better version with minor markup change,
下面是一个稍微好一点的版本,稍有标记更改,
$('#selectAllDomainList').click(function() {
var checkedStatus = this.checked;
$('#domainTable tbody tr').find('td:first :checkbox').each(function() {
$(this).prop('checked', checkedStatus);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<table id="domainTable">
<!-- Added ID -->
<thead>
<tr>
<th>
<!-- Added ID to below select box -->
<input type="checkbox" name="selectAll" id="selectAllDomainList" />
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" name="domainList" value="${domainInstance.id}" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="domainList" value="${domainInstance.id}" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="domainList" value="${domainInstance.id}" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="domainList" value="${domainInstance.id}" />
</td>
</tr>
</tbody>
<table>
回答by Ray
$("input:checkbox").prop("checked", status);
回答by Nicola Peluchetti
to select all checkboxes with name = selectAll and set their status you can do
选择 name = selectAll 的所有复选框并设置它们的状态,你可以做
function selectAll(status) {
$('input[name=selectAll]').each(function(){
$(this).prop('checked', status);
});
}