Hari Subramaniam
Hari Subramaniam

Reputation: 1876

datatables - Custom sorting a column with datetime and string

I am working with jquery datatables and i have a column that contains a combination of these values. A date, a string 'A' and another string 'B'. When i click on that column i want the column to be sorted with 'A' appearing first then sorted by date and then 'B' appearing next. Is there a way to achieve this functionality?

Upvotes: 1

Views: 4130

Answers (2)

Milina Udara
Milina Udara

Reputation: 597

Client Side :

$.extend($.fn.DataTable.ext.oSort, {
   /*
   *
   *custom_date sorting
   */
    "custom_date": function (a) {
        return a;
    },
    "custom_date-asc": function (x, y) {
        var x = getCustomEuroDateValue(x);
        var y = getCustomEuroDateValue(y);
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    },
    "custom_date-desc": function (x, y) {
        var x = getCustomEuroDateValue(x);
        var y = getCustomEuroDateValue(y);
        return ((x < y) ? 1 : ((x > y) ? -1 : 0));
    },
});
function getCustomEuroDateValue(strDate) {
   // return a string by spiting and merging the date as you need
   // B A 02/11/2013 to A20131102B
   //
   // Example : 
   // var frDatea = $.trim(strDate);
   // var frDatea1 = frDatea.split(' ');
   // var frDatea2 = frDatea1[2].split('/');
   // var x = (frDatea1[1] + frDatea2[2] + frDatea2[1]+ frDatea2[0] + frDatea1[0]);
   // return x;


}

Then add this to your otable properties

"aoColumns": [ {  }, { },{ "sType": "custom_date" },{ } ], 

Upvotes: 1

Jay Rizzi
Jay Rizzi

Reputation: 4304

If using client side, detect the DataTables sort listener and then attach your own that calls http://www.datatables.net/ref#fnSort

This is much easier to achieve using server-side with database, as you can always include a static order by clause in your select statement as the secondary sort option

post some more code if additional help is needed

Upvotes: 0

Related Questions