Add row after selected row in jQuery dataTables

DataTable is defined as

var oTable = $('#table1').dataTable({ 'aaData': [ ['John', 'ABC', '$90000'], ['Doe', 'XYZ', '$100000'], ['Alan', 'PQR', '$110000'] ], 'aoColumns': [ {'sTitle': 'Name'}, {'sTitle': 'Company'}, {'sTitle': 'Salary'} ] }); 

An empty string is added as

 oTable.fnAddData([' ', ' ', ' ']); 

However, this adds the bottom of the table. Is there a way that we can add exactly below / above the selected row.

+2
source share
2 answers

Think that you are too hasty to agree that you cannot do what you want :) Of course, this is possible, but it is difficult to determine under what circumstances. The question is not very specific. The following code inserts a new line immediately after the last line you clicked:

 var dataTable; var options = { bSort: false, bPaginate: false }; function initDataTable() { dataTable = $('#example').dataTable(options); } function attachClickHandler() { $("#example tbody tr").click(function(event) { var index=$(this).index(); $("#insert").text('insert a row below the row you just clicked ('+index+')').attr('index',index).show(); }); } $("#insert").click(function() { var index=$(this).attr('index'); var newRow = '<tr>'+ '<td>new</td>'+ '<td>new</td>'+ '<td>new</td>'+ '<td>new</td>'+ '<td>new</td>' + '</tr>'; dataTable.fnDestroy(); $("#example tbody tr").eq(index).after(newRow); initDataTable(); attachClickHandler(); }); initDataTable(); attachClickHandler(); 

The idea is to insert a new row into the underlying DOM table and then reinitialize the dataTable when it is done. It also works by sorting, but for demo purposes, I sort the sorting. As @scottysmalls mentions, dataTables really sorts everything, so the new inserted row will be sorted immediately, and it will look like it was not inserted correctly.

See demo -> http://jsfiddle.net/2AqQ6/

+4
source

I do not think this is possible without some custom sorting functions. The position is completely based on sorting. The developer supports this here: http://bit.ly/1gtYHyk and here http://bit.ly/PxHKgM

+1
source

All Articles