Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTable sorting by month number with month name as a data

I have a table which have the first column as a month-name (January, February ...), and I want to sort the rows according to number of month. January is first, after that February and so on.

If i do

table.fnSort([[ 0, "asc"]]);

I get the table sorted by the name of the month.

Eventually, I got this http://drmsite.blogspot.co.il/2013/08/datatables-custom-sort-by-month-name.html , but it only work when i click on the column's title. I need the table to be sorted by month-number when it loads. Can anyone help me?

like image 248
AntonCool Avatar asked Nov 30 '25 05:11

AntonCool


1 Answers

You can implement your own sorting plugin to do that. It is quite simple. Here I have defined a month array and before sorting I am returning the index not the month.

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
    "date-range-pre": function ( a ) {
        var monthArr = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        return monthArr.indexOf(a); 
    },
     "date-range-asc": function ( a, b ) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },
     "date-range-desc": function ( a, b ) {
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
} );

// Apply date-range sorting with your DataTable init
var table = $('#example').DataTable({ // example is your table id
    columnDefs: [
       { type: 'date-range', targets: 0 }
    ]
}) 

Here is a working demo.

like image 128
Deepak Biswal Avatar answered Dec 01 '25 19:12

Deepak Biswal