javascriptloopskendo-uikendo-griddataitem

Kendo Grid.dataItem loop not working


So my aim it to loop through all selected item in my kendo grid, but after the first iteration the dataItem method returns undefined.

function myFunction() {
var selectedItem = $("#DropDown").val();
var grid = $("#Grid").getKendoGrid();
var selectedItems = grid.select();
for (var i = 0; i < selectedItems.length; i++) {
    var dataItem = grid.dataItem(selectedItems[i]);
    if (dataItem != undefined)
        dataItem.set("Item", SelectedItem);
}
}

Does anyone know why this might be happening?


Solution

  • That happens because set() performs a grid refresh behind-the-scenes so the DOM is recreated. The array you had with the selected items is lost. You can't rely on the tr's references. As a suggestion I think you can use they indexes instead:

    function myFunction() {
        var selectedItem = $("#DropDown").val();
        var grid = $("#Grid").getKendoGrid();
        var selectedItems = grid.select().toArray().map((item) => { return $(item).index(); });
    
        for (var i = 0; i < selectedItems.length; i++) {
            var currentItem = grid.tbody.find(`tr:eq(${selectedItems[i]})`);
            var dataItem = grid.dataItem(currentItem );
            if (dataItem != undefined)
                dataItem.set("Item", SelectedItem);
        }
    }
    

    Demo