First of all, I'm a javascript noob, so my code is neither pretty nor smart. :(
I have a pretty basic Kendo grid to which I added two columns. The first column contains a checkbox (I call them minionCheckBox), the second contains a bool (from the data source), I'll call this one isChecked and the default is set to false.
Also I have a masterCheckBox in the table header which should toggle all minions.
Both checkbox types are added like this:
@(Html.Kendo().Grid<MVC5KendoTestWeb.Models.DTOs.DTO_User>()
.Name("TestGrid")
.Columns(columns =>
{
columns.Template(@<text></text>)
.HeaderTemplate("<input class='checkbox masterCheckBox' type='checkbox' /> <strong>Alle</strong>")
.ClientTemplate(@"
<input class='checkbox minionCheckBox' type='checkbox' data-bind='checked: isChecked' #= isChecked ? checked='checked' : '' # />")
.Width(80);
columns.Bound(cn => cn.isChecked).HtmlAttributes(new { @class = "isChecked" });
})
.DataSource(dataSource => dataSource
.Ajax()
.Create(create => create.Action("CreateUserData", "XXX"))
.Read(read => read.Action("ReadUserData", "XXX"))
.Update(update => update.Action("UpdateUserData", "XXX"))
.Destroy(destroy => destroy.Action("DestroyUserData", "XXX"))
.Model(model =>
{
model.Id(cn => cn.ID);
})
.PageSize(20)
.ServerOperation(true)
)
.Editable(editable => editable.Mode(GridEditMode.PopUp))
)
I want to change the value of isChecked whenever I toggle the checkbox in the same row. This seems to work as I intended with the following code:
var grid = $("#TestGrid").data("kendoGrid");
grid.tbody.on("change", function (e) {
var isMinionChecked = $(e.target).prop("checked");
var row = $(e.target).closest("tr");
var item = grid.dataItem(row);
if (isMinionChecked) {
item.set("isChecked", true);
} else {
item.set("isChecked", false);
}
if (!item.isChecked) {
var isMasterChecked = $(".masterCheckBox").prop("checked");
if (isMasterChecked) {
$('.masterCheckBox').prop('checked', false);
}
}
})
And here is my problem: Now I want to do the same for all rows whenever I check the masterCheckBox. This is my code for that:
var grid = $("#TestGrid").data("kendoGrid");
$(".masterCheckBox").on("click", function () {
var isMasterChecked = $(".masterCheckBox").prop("checked");
grid.table.find(".minionCheckBox").each(function () {
var row = $(this).closest("tr");
var item = grid.dataItem(row);
if (isMasterChecked) {
$(this).prop("checked", true);
item.set("isChecked", true);
} else {
$(this).prop("checked", false);
item.set("isChecked", false);
}
})
})
But, it only toggles the checkbox in the first row and sets the isChecked in that row to true. When I remove the two item.set lines, it works perfectly and checks or unchecks all checkboxes.
I know the code is not perfect yet and also I need to add a few more things, but as I see it, this should at least do these two things by now: toggle all checkboxes and set all isChecked fields to the right value.
Can someone help me figure this one out?
Aucun commentaire:
Enregistrer un commentaire