Intro

Useful DataTables.js code snippets.

Update Rank

Redraw rankings based on other column order. By configuring rank_asc and rank_desc variables you can make sure that rank column will be updated in the order that you need.

Usage: Add class="rank" data-rank="'+data.rank+'" to your rank column in DataTables configuration

JS Code


dataTable = data.length; //total lenght or data array

dataTable.on( 'order.dt', function () {
               
    var table = dataTable.order();
    column = table[0][0];
    order = table[0][1]; 
    rank_asc = [];
    rank_desc = [2,3,4,5];  
 
    if(rank_asc.includes(column)) sort_case = order;
    else if(rank_desc.includes(column) && order == 'desc') sort_case = 'asc';
    else if(rank_desc.includes(column) && order == 'asc') sort_case = 'desc';
    else sort_case = false;

    if(sort_case == 'asc') $('#dataTable .rank').each(function(i,v){ $(this).html(i+1); }); 
    else if(sort_case == 'desc'){ 

    max = regionsTotal + 1;
    $('#dataTable .rank').each(function(i,v){
      max -= 1;
      $(this).html(max);
    });

    }else $('#dataTable .rank').each(function(i,v){ $(this).html($(this).data('rank')); });

} ); 

             

Order Sequence

Change order sequence of DataTables.js. For e.g. start ordering table rows in descending order instead of default ascending order.

JS Code

orderSequence: [ "desc", "asc" ],