Pipo
Pipo

Reputation: 5599

How to loop through all rows in DataTables jQuery?

I am using jquery plugin DataTables for building nice table

  var table = $('#example').DataTable({
    "data": source
});

I would like that make an each for all rows in table

Unfortunately this way may be out of date and does't work with new version (it launchs an error)

$(table.fnGetNodes()).each(function () {

});

And this way only works only for visibles rows (10 first rows because other rows are paginated)

 table.each( function ( value, index ) {
    console.log( 'Data in index: '+index+' is: '+value );
} );

Do you known how to loop to all rows please?

Upvotes: 29

Views: 114285

Answers (4)

Asad Naeem
Asad Naeem

Reputation: 636

for example, this data has three fields UserID, UserName and isActive and we want to show only active users The following code will return all the rows.

var data = $('#myDataTable').DataTable().rows().data();

We will print only active users

data.each(function (value, index) {
  if (value.isActive)
  {
     console.log(value.UserID);
     console.log(value.UserName);
  }
});

Upvotes: 2

Pipo
Pipo

Reputation: 5599

I finally found:

 var data = table.rows().data();
 data.each(function (value, index) {
     console.log(`For index ${index}, data value is ${value}`);
 });

Upvotes: 44

Mohd Abdul Mujib
Mohd Abdul Mujib

Reputation: 13928

If you are using the legacy DataTables then you can get all the rows even the paginated ones, as shown below...

table.fnGetNodes(); // table is the datatables object.

So we can loop through the rows by using .each() method provided by jQuery.

jQuery(table.fnGetNodes()).each(function () {
// You can use `jQuery(this).` to access each row, and process it further.            
});

Upvotes: 7

Athman
Athman

Reputation: 594

Datatables have an iterator for each row rows().every() with this referring to the context of the current row being iterated.

tableName.rows().every(function(){
    console.log(this.data());
});

Upvotes: 13

Related Questions