Kendo网格更改多个选定的单元格值

时间:2014-03-11 15:32:32

标签: javascript jquery kendo-ui kendo-grid

假设我有几行填充数字的数据。我想选择多个单元格然后单击网格外的按钮将其值更改为其他数字,让我们说'8'。请参阅sample

Telerik的那些人给了我这个解决方案:

$(".change").click(function () {
    var grid = $("#Grid").data("kendoGrid");
    var cellsToChange = grid.select();

    for (var i = 0; i < cellsToChange.length; i++) {
        var item = grid.dataItem($(cellsToChange[i]).closest("tr"));
        item.ProductName = "new value";
    }

    grid.refresh();
});

但问题是我不知道将选择哪些单元格,因此我无法使用item.ProductName。有没有办法直接设置所有选定单元格的值,如cellsToChange[i].value

2 个答案:

答案 0 :(得分:3)

您可以从grid.columns或相应的th元素中获取列名称。使用grid.cellIndex方法选择正确的列:

$("#change").click(function() {
    var selected = grid.select();
    var header = grid.thead;
    for (var i = 0, max = selected.length ; i < max ; i++) {
        var index = grid.cellIndex(selected[i]);
        var th = $(header).find("th").eq(index);
        // could also use grid.columns[index].field 
        // (not sure if this gets reordered on column reorder though)
        var field = $(th).data("field");

        var item = grid.dataItem($(selected[i]).closest("tr"));
        item[field] = "new value";
    }

    grid.refresh();
});

关于你的评论: dataItem.set()导致<tr>元素从其上下文中删除(因为grid.refresh()将为视图创建新行),因此,grid.dataItem()赢得了\ t使用您仍然可以引用的旧DOM元素为您提供预期的结果。

如果你想使用dataItem.set(),你可以尝试这样的事情作为解决办法:

$("#change").click(function () {
    var selected = grid.select(),
        header = grid.thead,
        dataItem,
        index,
        field,
        value,
        th;

    for (var i = 0, max = selected.length; i < max; i++) {
        dataItem = grid.dataItem($(selected[i]).closest("tr"));
        index = $(selected[i]).index();
        th = $(header).find("th").eq(index);
        field = $(th).data("field");
        value = "new value " + i;

        setTimeout(function (dataItem, field, value) {
            return function () {
                dataItem.set(field, value);
            }
        }(dataItem, field, value), 5);
    }
});

demo

答案 1 :(得分:0)

您必须首先检索网格的ColumnList,然后循环遍历

$(".change").click(function () {
    var grid = $("#Grid").data("kendoGrid");
    var columnsListOfView = grid.columns;
    var cellsToChange = grid.select();

    for (var j = 0; i < cellsToChange.length; i++) {
        var item = grid.dataItem($(cellsToChange[i]).closest("tr"));
        for (var j = 0; j < columnsListOfView.length; j++) {
         //Here columnsListOfView[j].field will give you the different names that you need 
         var field=columnsListOfView[j].field;
         item[field] = "new value";    
        }
    }

    grid.refresh();
});