Deleting multiple rows
I'm using datatables, and I have selected multiple rows and I want to perform delete operation on multiple rows. For example, I selected rows 2, 3, and 4, so I want all the 3 rows to be deleted at the same time.
<script>
var oTable;
var giRedraw = false;
$(document).ready(function() {
/* 开发者_Python百科Add a click handler to the rows - this could be used as a callback */
$('#example tr').click( function() {
if ( $(this).hasClass('row_selected') )
$(this).removeClass('row_selected');
else
$(this).addClass('row_selected');
} );
/* Add a click handler for the delete row */
$('#delete').click( function() {
var anSelected = fnGetSelected( oTable );
oTable.fnDeleteRow( anSelected[0] );
} );
/* Init the table */
oTable = $('#example').dataTable( );
} );
function fnGetSelected( oTableLocal )
{
var aReturn = new Array();
var aTrs = oTableLocal.fnGetNodes();
for ( var i=0 ; i<aTrs.length ; i++ )
{
if ( $(aTrs[i]).hasClass('row_selected') )
{
aReturn.push( aTrs[i] );
}
}
return aReturn;
}
</script>
Through this script only 1 row gets deleted at a time.
Try this.
$('#delete').click( function() {
var anSelected = fnGetSelected( oTable );
oTable.fnDeleteRow( anSelected );
// previously it was anSelected[0] which select only frist element
} );
Edited
I made some changes in the fnGetSelected() function. Might that help
function fnGetSelected( oTableLocal )
{
var aReturn = new Array();
var aTrs = oTableLocal.fnGetNodes();
for ( var i=0 ; i<aTrs.length ; i++ )
{
// removed $() because this is already DOM element.
if ( aTrs[i].hasClass('row_selected') )
{
aReturn.push( aTrs[i] );
}
}
return aReturn;
}
精彩评论