dashevsk
dashevsk

Reputation: 61

Check if any row is selected in jQuery DataTables

I am trying to write a function to check if any of the table rows are selected.

I need this function to be triggered at any <tr> click.

Thank you.

Here is my code for selecting rows:

$('#Request tbody').on('click', 'tr', function () {
     if ($(this).hasClass('selected')) {
          $(this).removeClass('selected');
     } else {
          oTable.$('tr.selected').removeClass('selected');
          $(this).addClass('selected');
     }
});

Upvotes: 6

Views: 20569

Answers (4)

Tyler V
Tyler V

Reputation: 323

var table = $('#foo-table').DataTable();
var selectedRows = table.rows({ selected: true });

This is proper way to get the selected rows as of DataTables 1.10.8.

Upvotes: 1

Gyrocode.com
Gyrocode.com

Reputation: 58900

You have answer in your question already. The code below would let you determine if there are any selected rows.

var $rows = oTable.$('tr.selected');

// If some rows are selected
if($rows.length){

// Otherwise, if no rows are selected
} else {

}

I assume that somewhere in your code you have var oTable = $('#Request').DataTable(). Otherwise you can use $('#Request').DataTable().

Upvotes: 1

corpico
corpico

Reputation: 637

As of Datatables 1.10, there is an any() method that can be used:

var table = $('#example').DataTable();

if ( table.rows( '.selected' ).any() )
    // Your code here

Upvotes: 13

Tal
Tal

Reputation: 81

Using the API.

var oTable = $("#yourtable").DataTable();

anyRowSelected = oTable.rows({selected : true}).indexes().length === 0 ? false : true;//false - nothing selected. true - 1 or more are selected.

Upvotes: 0

Related Questions