Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTables loop through the table and delete all rows that contain certain string in certain column

Been trying to work this out for a while:

In column under index 6 in my DataTable, I have a boolean on Croatian language -> DA for 1 and NE for 0. At one point I want to fire a procedure that will delete all rows that contain "DA" in the column under index 6, however, after the following procedure:

function deleteSelectedDiscountedProducts() {
    tableSelectedProducts.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
        var currentData = this.data();
        if (currentData[6].indexOf("DA") >= 0) {
            tableSelectedProducts.row(rowIdx).remove().draw(false);
        } else {

        }
    } );
}

I get only one row deleted (probably the first one detected) and the following in the console:

Uncaught TypeError: Cannot read property '6' of undefined

Also, I tried switching tableSelectedProducts.row(rowIdx).remove().draw(false); with this.remove().draw(false); and it does absolutely the same error deleting only the first row it detects.

What is happening in the background and how to solve this? It seems to me that after deleting one row all the data from the datatable doesn't exist anymore (column under index 6 is undefined) and when I tried to console.log(this) for each of the rows detected, I don't get any output after the first detected row is deleted, but an error above.

like image 267
Alen Šimunic Avatar asked Jan 29 '23 18:01

Alen Šimunic


1 Answers

It is bad practice to delete array items by their indexes in a loop. Once you have deleted one item all indexes may have been changed. It is better to pick up a list of the row dom nodes you want to delete, and then delete them. Here is an example :

$('#delete').on('click', function() {
  var nodes = [];
  table.rows().every(function(rowIdx, tableLoop, rowLoop) {
    if (this.data()[3] == 'Edinburgh') nodes.push(this.node())
  })
  nodes.forEach(function(node) {
    table.row(node).remove().draw()
  })
})

demo -> http://jsfiddle.net/LqzLzxon/

like image 144
davidkonrad Avatar answered Feb 01 '23 08:02

davidkonrad