Can the jquery dataTables plugin respect alternate row colors after sorting/filtering?

leora picture leora · Jun 11, 2015 · Viewed 19.7k times · Source

I am using jquery datatables plugin which seems like a useful plugin to take a regular html table and add sorting, filtering, paging, etc

One issue i see is that when i search it doesn't seem to update the "odd" / "even" row classes so if my table has 100 rows but when i filter it has 10 it might be that all 10 are the same backcolor or 8 are the same backcolor

I see the same issue after i sort by a column as well where it might "bunch up" a bunch of rows with teh same backcolor after I sort by a column.

Is there anyway that the datatables plugin can reapply even/odd styling after the filter so no matter what you are filtering, there is always alternate row backcolor?

Answer

Gyrocode.com picture Gyrocode.com · Jul 6, 2015

CAUSE

This functionality is available by default. Most likely the reason for this unusual behavior:

  • you override odd and even classes in your CSS, or
  • your code affects table structure after filtering

SOLUTION #1

  1. Default styling or jQuery UI or Foundation

    Use class display for your <table> as shown below. See Default styling options for a list of all available classes.

     <table id="example" class="display" cellspacing="0" width="100%">   
    

    See this jsFiddle for demonstration.

  2. Bootstrap

    Use classes table table-striped table-bordered for your <table> as shown below:

     <table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
    

    See this jsFiddle for demonstration.

SOLUTION #2

If there is a CSS rule that overrides odd and even classes you can instruct jQuery DataTables to use alternative classes instead with stripeClasses option.

$('#example').DataTable( {
  "stripeClasses": [ 'odd-row', 'even-row' ]
} );