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?
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:
table.data()
data arraylet newdata = Array.from(table.data());
newdata.unshift(['my', 'new', 'row']);
table.clear();
for (const row of newdata) {
table.row.add(row);
}
table.draw();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With