我有一张表,上面有一列复选框。在顶部,我想有一个单一的“全选”复选框,将选中该页上的所有复选框。
我应该如何实现它?如果重要的话,我使用jQuery作为我的JavaScript框架。
发布于 2009-08-01 06:49:57
这将使所有单个复选框与"check all“复选框相同
$("#id-of-checkall-checkbox").click(function() {
$(".class-on-my-checkboxes").attr('checked', this.checked);
});
这将使“全部选中”复选框与单个复选框实际上是否全部选中保持同步
$(".class-on-my-checkboxes").click(function() {
if (!this.checked) {
$("#id-of-checkall-checkbox").attr('checked', false);
}
else if ($(".class-on-my-checkboxes").length == $(".class-on-my-checkboxes:checked").length) {
$("#id-of-checkall-checkbox").attr('checked', true);
}
});
发布于 2009-07-31 17:46:06
jquery (编辑的可切换勾选/取消勾选全部):
$(document).ready(function() {
$("#toggleAll").click(function() {
$("#chex :checkbox").attr("checked", $(this).attr("checked"));
});
});
我必须先执行click()
,然后检查checked
状态的原因是,如果您尝试"toggle
“一个复选框,被切换的复选框将不会保持其选中状态。这样,它将保留检查状态并有效地切换。
HTML:
<input type="checkbox" id="toggleAll" />
<div id="chex">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
发布于 2019-08-07 04:32:25
对我来说,杰里米的解决方案大部分是有效的,,但我不得不用.prop
取代 .attr
。否则,一旦我单击了一个复选框,它就会停止对"master“复选框的反应。
_Layout.cshtml (母版页)中的
$(document).ready(
manageCheckboxGroup('chkAffectCheckboxGroup', 'checkbox-group')
);
引用的.js中的
function manageCheckboxGroup(masterCheckboxId, slaveCheckboxesClass) {
$("#" + masterCheckboxId).click(function () {
$("." + slaveCheckboxesClass).prop('checked', this.checked);
});
$("." + slaveCheckboxesClass).click(function () {
if (!this.checked) {
$("#" + masterCheckboxId).prop('checked', false);
}
else if ($("." + slaveCheckboxesClass).length == $("." + slaveCheckboxesClass + ":checked").length) {
$("#" + masterCheckboxId).prop('checked', true);
}
});
}
超文本标记语言(剃刀)页面中的
<table class="table">
<thead>
<tr>
<th><input id="chkAffectCheckboxGroup" type="checkbox" checked="checked" /></th>
<th>
@Html.DisplayNameFor(model => model.Clients[0].ClientId)
</th>
<th>
@Html.DisplayNameFor(model => model.Clients[0].Name)
</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Clients.Count(); i++)
{
<tr>
<td>
<input type="hidden" asp-for="Clients[i].Id" class="form-control" />
<input type="hidden" asp-for="Clients[i].Name" />
<input type="checkbox" class="checkbox-group" asp-for="Clients[i].Selected" />
</td>
<td>
@Html.DisplayFor(modelItem => Model.Clients[i].Id)
</td>
<td>
@Html.DisplayFor(modelItem => Model.Clients[i].Name)
</td>
</tr>
}
</tbody>
</table>
重要提示:还有,一开始我在超文本标记语言中有一个@foreach
循环,但是它不起作用...,你必须使用@for (int i = 0; i < Model.Clients.Count(); i++)
循环,否则你在OnPostAsync()
中会得到一个空的列表。
https://stackoverflow.com/questions/1213908
复制相似问题