remove multiples rows from datatable based on their respective indexes in jquery

remove multiples rows from datatable based on their respective indexes in jquery

waweru99 karanjawaweru99 karanja Posts: 17Questions: 5Answers: 1

I want to remove some rows from datatable based on their respective indexes.The indexes are in form of an array. Upon clicking a button the function gets the array and finds each of them in the datatable then remove them .I have been able to create the code and its able to execute perfectly.Now the issue is not all the rows are removed,lets say we have 5 rows that we want to remove only 2 rows are removed.How can i remove all the rows in the table with all the respective indexes.This is my code

       var productsIds=['2','3','4','5','6']

       productsIds.forEach(function(id) {
           var columnIndex = 0;
           var rowIndex = productsTable.column(columnIndex).data().indexOf(id);
           productsTable.row(rowIndex).remove();
       });

       productsTable.draw();

Replies

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    The basic idea is okay, but I think line 5 looks "off". Are you sure you want to use the data index and not a property in the data such as a primary key value. That is 100% what I would recommend since the index is meaningless other than for the data that was loaded in. For example, it could change on a reload!

    If would help if you link to a test case showing the issue so I can see the data and setup in question.

    Allan

  • waweru99 karanjawaweru99 karanja Posts: 17Questions: 5Answers: 1

    hello allan here is a link for the table
    https://live.datatables.net/gaboqoxo/497/

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Super thank you. So the id is a value in the table's data set. That being the case, I would use a row selector (row-selector) as a function to match the id:

      var productsIds=['2','3','4','5','6']
     
      var productsTable = $('#productsTable').DataTable();
      
      productsIds.forEach(function (productId) {
        productsTable.row((idx, data) => data[0] === productId).remove();
      });
      
      productsTable.draw();
    

    i.e. for each item in the productsIds array, find the row with the matching id, and then remove it.

    https://live.datatables.net/gaboqoxo/498/edit

    Allan

Sign In or Register to comment.