![](/img/trans.png)
[英]JQuery multiple select control with css class in asp.net MVC 4
[英]select one or multiple or all checkbox with jquery (ASP.NET MVC)
我在ASP.NET MVC项目中有一个表,其中有一个带复选框的表。 该表是从数据库生成的,每个循环都有一个。 桌子看起来像这样
<table id="customertable">
<thead>
<tr>
<th>Customer Name</th>
<th>Date of Birth</th>
<th>Age</th>
<th>
<div class="btn-group pull-left">
<input id="checkAll" type="checkbox" autocomplete="off"/>
</div>
</th>
</tr>
</thead>
<tbody>
@foreach (var item in ViewBag.Customer)
{
<tr>
<td id="@item.CustomerID">@item.CustomerName</td>
<td>@item.DateOfBirth</td>
<td>@item.Age</td>
<td class="col-md-2" align="right">
<div class="btn-group pull-left">
<input class="customerCheck" type="checkbox" autocomplete="off"/>
</div>
</td>
</tr>
}
</tbody>
</table>
在这里,我为表中的每一行都有一个复选框,在表头中,我有一个复选框可以一次检查所有这些。
我可以检查所有这些人,并使用类似这样的脚本获取其ID
$('#customerTable #checkAll').click(
function () {
//save state of checkall checkbox
var chk = $('#checkAll').is(':checked');
//check state of checkall checkbox
if (chk !== false) {
//change all other checkbox to this state
$('.customerCheck').prop('checked', true);
//loop through all checked customer
$('.customerCheck').each(function () {
//get value of first html element
var seeID = $('#customertable tr td').map(function () {
//get the customerID and create a comma separated string
var cellText = $(this).attr('id');
return cellText;
}).get().join();
$("#customerID").val(seeID);
$("#CustomerID").attr('value', seeID);
});
} else {
//remove all checked checkbox
$('.customerCheck').prop('checked', false);
$('.customerCheck').each(function () {
$('#customertable tr td').each(function () {
$(this).attr('value', '');
});
$("#customerID").attr('value', '');
});
}
}
我将输出作为逗号分隔的字符串
<input class="form-control" id="customerID" name="customerID" type="text" value="" />
现在,我的问题是尽管我可以同时检查所有内容,但不能检查一个或多个(但不是全部),并在我的输出字段中将它们各自的ID作为逗号分隔值输出。 我该如何解决? 请帮忙。
解决方案是将ID添加到复选框输入id="@item.CustomerID"
,然后遍历所有复选框以查看选中了哪些复选框。
//in loop
<td class="col-md-2" align="right">
<div class="btn-group pull-left">
<input id="@item.CustomerID" name="getCustomerID" class="customerCheck" type="checkbox" value="@item.CustomerID" autocomplete="off" />
</div>
</td>
//click on checkbox (any)
$('.customerCheck').click(function () {
//see all the checked checkboxs and loop through them
$('input[type=checkbox]:checked').each(function () {
//get their id and make it a comma separated string
var sSheckID = $('input[type=checkbox]:checked').map(function () {
return $(this).attr('id');
}).get().join();
//set is as the value of the output box.
$("#CustomerID").val(sSheckID);
$("#CustomerID").attr('value', sSheckID);
});
});
//output
<input class="form-control" id="customerID" name="MCustomerID" type="text"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.