Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery datatables remove row by index

I know this question is popular but all answers are for selected rows. I am trying to delete / remove a row that is NOT selected. I have a variable for the table that I want to remove the row from and I have the index of the row that I want to remove.

These are various ways to get a handle to the table or rows:

var table = $('#tableName');
var rows = $('#tableName tbody tr').toArray();
var oTable = $('#tableName').dataTable();

I know how to use the row.remove() method on a selected row.

var jThisButton = $(this);
var jRow = jThisButton.parents("tr");
jRow.remove();

But my row is NOT selected; instead I have an index. Let's say my index is 2. Using something like the above code, perhaps I can get row by index and remove it like this:

var jRow = table.find('tr').eq(index);
jRow.remove();

Except that does not work. That code moves the row I want to delete to the last row and goes wonky, showing the search bar.

enter image description here

You can see in the image below that I have 4 rows in the table.

How do I remove the tr that exists at index 2?

enter image description here

I have not been able to find the answer to this question anywhere. Please help!

like image 713
Patricia Avatar asked Sep 21 '17 20:09

Patricia


1 Answers

Try this:

oTable.row(index).remove().draw();

Removing the tr from the DOM will not remove it from DataTable. If the DataTable is drawn once again, the deleted rows will return to view.

The remove() will remove the row from DataTable and calling draw() will update the DataTable. This will also update the row count information.

UPDATE

For DataTable 1.9.4 the below code will work

oTable.fnDeleteRow(index);

draw() is not required as the DataTable is refreshed after fnDeleteRow()

like image 195
Binu Purushothaman Avatar answered Oct 02 '22 23:10

Binu Purushothaman