[英]How to find a single checkbox's checked state in a WebGrid
這是我的WebGrid,其中包含ID = chkbox1的復選框列:
@grid.GetHtml(htmlAttributes:=New With {.id = "grid", .class = "table table-bordered table-striped table-condensed", .name = "grid1"},
emptyRowCellValue:="No Records Found",
headerStyle:="grid-header",
columns:=grid.Columns(
grid.Column(header:="Select", format:=Function() Html.CheckBox("chkboxname", htmlAttributes:=New With {.id = "chkbox1", .value = "Item"})),
grid.Column("item_id", "Item ID"),
grid.Column("item_desc", "Description")))
這是將WebGrid轉換為json對象的函數:
<script>
document.getElementById("btnGetRows").addEventListener("click", getTableData);
function getTableData() {
//debugger;
var _griddata = gridTojson();
var url = '@Url.Action("GetGridViewRows")';
alert(_griddata);
$.ajax({
url: url,
type: 'POST',
data: { griddata: _griddata }
}).done(function (data) {
if (data != "") {
$('#grid').html(data);
}
});
}
function gridTojson() {
var json = '{';
var otArr = [];
var tbl2 = $('#grid tbody tr').each(function (i) {
var chkbox2 = $("#chkbox1").is(":checked");
//var chkbox = document.getElementById("chkbox1"); //tried this too
if ($(this)[0].rowIndex != 0) {
if (chkbox2) {
x = $(this).children();
var itArr = [];
x.each(function () {
if ($(this).children('input').length > 0) {
itArr.push('"' + $(this).children('input').val() + '"');
}
else {
itArr.push('"' + $(this).text() + '"');
}
});
otArr.push('"Row' + i + '": [' + itArr.join(',') + ']');
}
}
})
json += otArr.join(",") + '}'
return json;
}
</script>
我想要做的是遍歷並獲取選中了復選框的任何行,並將行數據存儲在json對象中。 如果我選中了WebGrid上的所有復選框,則“ if”語句變為true。 即使復選框具有相同的ID,由於var chkbox2 = $(“#chkbox1”)。is(“:checked”)處於循環中並且每次都將其重置,因此它是否仍不起作用?
訣竅是這樣做:
if ($(this).find("td").children().is(":checked")) {
x.each(function () {
if ($(this).children('input').length > 0) {
itArr.push('"' + $(this).children('input').val() + '"');
}
else {
itArr.push('"' + $(this).text() + '"');
}
});
}
代替這個:
var chkbox2 = $("#chkbox1").is(":checked");
if ($(this)[0].rowIndex != 0) {
if (chkbox2) {
x = $(this).children();
var itArr = [];
x.each(function () {
if ($(this).children('input').length > 0) {
itArr.push('"' + $(this).children('input').val() + '"');
}
else {
itArr.push('"' + $(this).text() + '"');
}
});
otArr.push('"Row' + i + '": [' + itArr.join(',') + ']');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.