DataTables row.add for specific index

I replace the string elements as follows:

var $targetRow = $(entity.row), dataTable = $targetRow.closest('table.dataTable').DataTable(); dataTable.row($targetRow).remove(); dataTable.row.add({ foo: 1 }).draw(); 

I have logic in the rowCreated bound to a table, so I recreate the row to use it. It works great. But row.add always adds the regenerated row, the last in the list. Is there a way to insert it into a specific index?

+2
source share
2 answers

dataTables contains its rows in an indexed array, and there are no API methods to add a new row to a specific index or change the index() row.

This really makes sense, since a typical dataTable is always sorted / ordered or filtered by data, not a static index. And when you get data from the server or want to transfer data to the server, you never use the static index() client.

But if you think about it, you can still order the rows and thereby insert a row with a specific index very simply using code, simply reordering the data. When a new row is added, replace the data from the last row (inserted row) with the second last row, then change the data from the second last row to the third last row and so on until you reach the index where you want to insert the row.

 [0][1][2][3][4->][<-newRow] [0][1][2][3->][<-newRow][4] [0][1][2->][<-newRow][3][4] 

Example: inserting a new row into the index on which the mouse is clicked:

 $("#example").on('click', 'tbody tr', function() { var currentPage = table.page(); //insert a test row count++; table.row.add([count, count, count, count, count]).draw(); //move added row to desired index (here the row we clicked on) var index = table.row(this).index(), rowCount = table.data().length-1, insertedRow = table.row(rowCount).data(), tempRow; for (var i=rowCount;i>index;i--) { tempRow = table.row(i-1).data(); table.row(i).data(tempRow); table.row(i-1).data(insertedRow); } //refresh the current page table.page(currentPage).draw(false); }); 

demo β†’ http://jsfiddle.net/mLh08nyg/

+10
source

Another way is to insert a row, and then move the row in the DataTable row array to the position you specified before redrawing the table:

 // Define the row to insert (using your method of choice) var rowInsert = $('#table-id').find('tr:last'); // Get table reference - note: dataTable() not DataTable() var table = $('#table-id').dataTable(); // Get api var dt = table.api(); // Insert row (inserted as the last element in aiDisplayMaster array) dt.row.add(rowInsert); // Get the array holding the rows var aiDisplayMaster = table.fnSettings()['aiDisplayMaster']; // Remove the last element in the array var moveRow = aiDisplayMaster.pop(); // EITHER add row to the beginning of the array (uncomment) //aiDisplayMaster.unshift(moveRow); // OR add row to a specific index (in this case to index 3) var index = 3; aiDisplayMaster.splice(index, 0, moveRow); // Redraw Table dt.draw(false); 
+3
source

All Articles