DataTables example Row selection and deletion (single row)

This example shows a modification of the multiple row selection example, where just a single can now be selected. This is done simply by checking to see if the row already has a selected class or not, and if so removing it, if not then the class is removed from any other row in the table which does have it and applied to the row to be selected.

Also shown is the row().remove() method which will delete a row from a table, and the draw() method with false as its first parameter. This will redraw the table keeping the current paging (without the false parameter the paging would be reset to the first page).

If you are looking for a more complete and easier to use row selection option, check out the Select extension provides an API that is fully integrated with DataTables for selecting rows and acting upon those selected rows.

The Javascript shown below is used to initialise the table shown in this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(document).ready(function() {
    var table = $('#example').DataTable();
 
    $('#example tbody').on( 'click', 'tr', function () {
        if ( $(this).hasClass('selected') ) {
            $(this).removeClass('selected');
        }
        else {
            table.$('tr.selected').removeClass('selected');
            $(this).addClass('selected');
        }
    } );
 
    $('#button').click( function () {
        table.row('.selected').remove().draw( false );
    } );
} );

In addition to the above code, the following Javascript library files are loaded for use in this example: