JianYA
JianYA

Reputation: 3024

Deleted selected rows from JQuery Datatables

How do I delete my selected rows from datatables that use a local array for data? This is how I initialised my table:

    var selected = Array();
    var dataSet = [];
    var rowItem = "";
    $(document).ready(function () {
        var table = $("#table").DataTable({
            "data": dataSet,
            "filter":false,
            "language": {
                "search": "",
                "searchPlaceholder": " Search"
            },
            "select": {
                "style": 'multi'
            },
            "ordering": true,
            "lengthChange": false,
            "columns": [
               { "title": "Name"},
            ],
            "responsive": true,
            "processing":true,
        }).columns.adjust()
        .responsive.recalc();
        new $.fn.dataTable.FixedHeader(table);

This is how I'm trying to delete the selected rows from my tables:

      $("#roleSection").on("click","#removeRole",function (e) {
            selected = table.rows('.selected').data().toArray();
            console.log(selected);
            $.each(selected, function (id, value) {
                console.log(value);
                dataSet.splice($.inArray(value, dataSet), 1);
                table.row(selected).remove().draw();
            });
            console.log(dataSet);
            return false;
        });

For some reason the items that are not deleted are being deleted and the table does not get updated at all.

Upvotes: 0

Views: 3155

Answers (1)

S. Patel
S. Patel

Reputation: 172

I think you can find your answer over here

  • Basically, you have to change your line selected = table.rows('.selected').data().toArray(); to table.rows( '.selected' ).remove().draw();
  • And remove the additional code.
  • You also don't have to worry about looping through the list because table.rows('.selected') gets all the rows with the class selected and then remove() deletes them all for you.

Edit: If the dataSet is not updated automatically, then I think this might answer your second query

$("#delete").on("click", function (e) {
  let newDataSet = [];
  table.rows( '.selected' ).remove().draw();
  table.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
    let row = this;
    newDataSet.push(row.data());
  });
  dataSet = newDataSet;
});

Upvotes: 2

Related Questions