1
votes

I want to get index of selected row in kendo grid. The code below returns index of a row based on current page. It does not obey the grid's page number and page size.
So if grid's page size is 50, you are on 2nd page and you click on 5th row then index should be 54 because you clicked on 55th row.

Both the options below does not work

Option 1

grid.on('click', '.t-doc', function (e) {
        var kendoGrid = $("#grid").getKendoGrid();
        var row = $(e.target).closest("tr");        
        var index = $("tr", kendoGrid.tbody).index(row);
}

Option 2

grid.on('click', '.t-doc', function (e) {
        var kendoGrid = $("#grid").getKendoGrid();
        var ds = kendoGrid.dataSource;
        var dataItem = kendoGrid.dataItem($(e.target).closest("tr"));
        var index = ds.indexOf(dataItem);
2
Another option: var selectedItem = grid.dataItem(grid.select());Steve Greene

2 Answers

0
votes

this is what i did. I hope there is better option

grid.on('click', '.t-doc', function (e) {
        var kendoGrid = $("#grid").getKendoGrid();
        var ds = kendoGrid.dataSource;
        var dataItem = kendoGrid.dataItem($(e.target).closest("tr"));
        var index = ((ds.page() - 1) * ds.pageSize()) + ds.indexOf(dataItem);
}
0
votes

As far as my research goes, there isn't a way to get the selected index in relation to your data list in one clean swoop. This is however an indexOf method to accomplish this, which works with multiple pages. Note that you first have to find the selected row as a dataItem. This is similar to your second method, however I am also using the grid.select() method to get the selected element, instead of the parent row. Here is what the code for this looks like:

function () {
  // Get the grid element
  var grid = $('#grid').data('kendoGrid');

  // Get the selected row as a dataItem
  var dataItem = grid.dataItem(grid.select());

  // Compute the index of the dataItem
  var index = grid.dataSource.indexOf(dataItem);

  // Do whatever you need with the index
}

Line for line, this isn't that much shorter, however it saves you from having to compute the index manually, which feels a bit cleaner. This works off of the auto-assigned guid value, so it should work with rows that were added later on by your user. Also, note that when there is no selected index, the index will be -1, and that the selected index is reset upon pagination. Hope that helps!