Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
172
rated 0 times [  176] [ 4]  / answers: 1 / hits: 19251  / 11 Years ago, wed, october 23, 2013, 12:00:00

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');
}*

More From » jquery

 Answers
10

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/


[#74782] Tuesday, October 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joep

Total Points: 32
Total Questions: 97
Total Answers: 104

Location: Wales
Member since Thu, Jul 1, 2021
3 Years ago
;