Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kendo UI Grid Inline - Insert new row at a specific position on the grid

I am trying to insert a new row via the addRow() method to the grid but I want it to be added AFTER the currently selected row on the grid OR BEFORE the currently selected row? Can anyone help with this please? At the moment all I got was:

Grid.addRow();

$(".k-grid-edit-row").appendTo("#Grid tbody");

But this inserts a row at the bottom of the table. I need it to add rows at specific positions with the grid which would already have rows.

like image 330
Simmy Dhanda Avatar asked Jul 24 '14 10:07

Simmy Dhanda


Video Answer


1 Answers

These are the steps:

  1. Get the selected item
  2. Get the item corresponding to the selected item.
  3. Get the index corresponding to the item that is selected.
  4. Use insert method in DataSource for specifying the position where you want to insert.

Code:

var grid = $("#grid").data("kendoGrid");
// Get selected item
var sel = grid.select();
// Get the item
var item = grid.dataItem(sel);
// Get the index in the DataSource (not in current page of the grid)
var idx = grid.dataSource.indexOf(item);
// Insert element before
grid.dataSource.insert(idx, { /* Your data */ });
// Insert element after
grid.dataSourcer.insert(idx + 1, { /* Your data */ });

See it in action here: http://jsfiddle.net/OnaBai/8J4kr/ 

EDIT If after inserting the row you want to enter that row in edit mode, you have to remember the position inside the page where you are inserting since editRow works at DOM level:

var grid = $("#grid").data("kendoGrid");
// Get selected item
var sel = grid.select();
// Remember index of selected element at page level
var sel_idx = sel.index(); 
// Get the item
var item = grid.dataItem(sel);
// Get the index in the DataSource (not in current page of the grid)
var idx = grid.dataSource.indexOf(item);
// Insert element before (use {} if you want an empty record)
grid.dataSource.insert(idx, { LastName: "Smith", FirstName: "John", City: "Baiona" });
// Edit inserted row
grid.editRow($("#grid tr:eq(" + ( sel_idx + 1) + ")"));    

For after you should do

// Insert element before (use {} if you want an empty record)
grid.dataSource.insert(idx + 1, { LastName: "Smith", FirstName: "John", City: "Baiona" });
// Edit inserted row
grid.editRow($("#grid tr:eq(" + ( sel_idx + 2) + ")"));  

See it in action here: http://jsfiddle.net/OnaBai/8J4kr/1/

There is an additional question that is that you might need to move to previous or next page depending if you are inserting before the first row of a page or after the last row of a page (use page for moving between Grip pages).

like image 96
OnaBai Avatar answered Sep 29 '22 18:09

OnaBai