Delete multiple selected DataTable rows with one c

2019-08-31 08:35发布

问题:

I am using an example from Datatables to delete rows from a table. This works fine, one by one but I need the ability to select and delete multiple rows. I commented the //.removeClass('row_selected'); so the user is visually able to select more than one row, but still the rows only delete one at a time. Ideas? https://datatables.net/release-datatables/examples/api/select_single_row.html

http://jsfiddle.net/BWCBX/22/

jQuery

var oTable;

$(document).ready(function() {
    /* Add a click handler to the rows - this could be used as a callback */
    $("#example tbody tr").click( function( e ) {
        if ( $(this).hasClass('row_selected') ) {
            $(this).removeClass('row_selected');
        }
        else {
            oTable.$('tr.row_selected')//.removeClass('row_selected');
            $(this).addClass('row_selected');
        }
    });

    /* Add a click handler for the delete row */
    $('#delete').click( function() {
        var anSelected = fnGetSelected( oTable );
        if ( anSelected.length !== 0 ) {
            oTable.fnDeleteRow( anSelected[0] );
        }
    } );

    /* Init the table */
    oTable = $('#example').dataTable( );
} );


/* Get the rows which are currently selected */
function fnGetSelected( oTableLocal )
{
    return oTableLocal.$('tr.row_selected');
}*

回答1:

This will delete multiple rows...

$('#delete').click( function() {
    var anSelected = fnGetSelected( oTable );
    $(anSelected).remove();
} );

This is preferable to using the in-built delete method in dataTables as it changed quite drastically at one point. Initially, it would retain row indexes between deletes, so you could delete row 1, then row 2, then row 3 etc.. It was then changed so that you could delete row 1, and row 2 would become row 1, so you'd have to delete row 1 again etc..

Using the above method just removes the rows from the table directly, which is much easier and will save you hassle if changing versions of dataTables at any time.

http://jsfiddle.net/BWCBX/23/



回答2:

Here my version, It will delete multiple row and update data info in the footer

$('#delete').click( function() {
    var anSelected = fnGetSelected( oTable );

    for (var i = 0; i < anSelected.length; i++) {
        oTable.fnDeleteRow(anSelected[i]);
    };
});

The Datatable have delete function row, but only 1 row. So I just looping it. The info will be updated too.

Showing 1 to 3 of 3 entries

here my code and demo

http://jsfiddle.net/BWCBX/95/