Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a new row to the top of a jQuery datatable

I need to add a new row into a datatable which should be placed in the top of the table and I've used sorting plugin, but it failed.

Can anyone please help me to fix this issue?

like image 611
Tony Jose Avatar asked Apr 10 '15 13:04

Tony Jose


2 Answers

In my case, the sort order of the table is whatever order the server returns the data array in. The client does not do any additional sorting ('ordering' is set to false). In order to add a new row to the beginning of the data array client-side, I did the following:

  • get the raw table.data() data array
  • insert my new row at the beginning of the array
  • clear the table and re-add all the rows
let newdata = Array.from(table.data());
newdata.unshift(['my', 'new', 'row']);
table.clear();
for (const row of newdata) {
  table.row.add(row);
}
table.draw();
like image 116
erwaman Avatar answered Sep 18 '22 12:09

erwaman


After quite some time I could solve this problem in my table with the built in order() function. (No additional plugin needed)

    var table = $('#adapterTable').DataTable();

    $('#newButton').on( 'click', function () {
        var row = ["<button id='savebutton'>save</button>","<input name='titel'/>"];
        table.row.add(row).draw( false );

        table.order([1, 'asc']).draw();
        table.order([0, 'asc']).draw();
    } );

This works because my table has ID's in the first column and text field in the second column.

My inserted row contains a save button in the ID column and an input field in the second column.

If I now sort the second Column ascending the input box will be shown on top. To restore the ordering by ID I just make one more order() on the ID column. This somehow doesn't affect the row with the button, just the rows with numeric values.

table.order([0, 'asc']).draw();

This also is more of a workaround and it depends on the content of your table. With plain Text you might have to combine it with a hidden column just for ordering, or another trick. But you can use datatable functions and don't need to manipulate the table directly.

like image 41
Yush0 Avatar answered Sep 16 '22 12:09

Yush0