[英]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.