![](/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.