Search code examples
jquerydatatable

Serverside dynamically addClass Datatables


NOTE - Datatable serverside processing with MySql database

and the code is as follows


$(document).ready(function(){
 var table = $('#userDataList').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": "fetchData.php",
        stateSave: 'true'
    });
});

Also the table / page available at

http://testlearn.infinityfreeapp.com/index-old.html

How to add a class to all

a) even rows dynamically.

b) odd columns dynamically.

(with or without a button click)


Solution

  • You can do this using rowCallback() on datatable initialisation.

    $(document).ready(function () {
      var table = $("#userDataList").DataTable({
        processing: true,
        serverSide: true,
        ajax: "fetchData.php",
        stateSave: "true",
        rowCallback: function (row, data, index) {
          if (index % 2 == 0) {
            $(row).addClass("oddRow");
          } else {
            $(row).addClass("evenRow");
          }
        },
      });
    });
    

    Use this CSS to see the difference

    table.dataTable tbody tr.evenRow{
        background-color: green;
    }
    table.dataTable tbody tr.oddRow{
        background-color: red;
    }
    

    Demo