Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatables add class to all body rows

I'm new in Datatables and I have a table that displays just the first 10 rows by default. I'm trying to add this class to all rows, not just for the default 10 ...

var table = $("#datatable-buttons").DataTable({...})
table.rows.removeClass('selected')

and

$('tbody tr').removeClass('selected')

and

$(tables.table().body()).removeClass('selected')

but without any success :( Is it possible to add/remove the select class to all rows just by clicking a button?

like image 317
Dana Avatar asked Apr 13 '17 20:04

Dana


1 Answers

I believe the best way to add a certain class to all rows is upon initialization :

var table = $('#example').DataTable({
  createdRow: function ( row, data, index ) {
     $(row).addClass('selected')
  } 
}) 

You can add/remove a class to a row upon click by using

table.on('click', 'tbody tr', function() {
  var $row = table.row(this).nodes().to$();
  var hasClass = $row.hasClass('selected');
  if (hasClass) {
    $row.removeClass('selected')
  } else {
    $row.addClass('selected')
  }
})

You can also by code remove (or add) a class to all rows by

table.rows().every(function() {
  this.nodes().to$().removeClass('selected')
})

All examples in action here -> http://jsfiddle.net/c67q2b4x/

like image 100
davidkonrad Avatar answered Oct 19 '22 11:10

davidkonrad