Uncategorized

Custom sorting with jQuery DataTable plugin

Okay, this is rather quick. I’m working on a project where I need to customize the DataTable UI to sort a column having some euro date formats. I know there are proper ways to do it but sometimes, proper method does not work for some weird circumstances and going with the proper way leads to delayed deliverables. I’ve copied some plugin to enable date sorting on DataTable column.

Assuming that we are using the DataTable plugin, all we need to do is to define a custom sorting callback. This is what I do. You can actually found this on the DataTable site on plugins section but I’ved hacked it to work on my project.

Below is the JavaScript snippet. Be sure to include this after the plugin included, not before. The name of our custom column sorting definition is custom_euro_date.

jQuery.fn.dataTableExt.oSort['custom_euro_date-asc'] = function(x, y) {
    var xVal = getCustomEuroDateValue(x);
    var yVal = getCustomEuroDateValue(y);

    if (xVal < yVal) {
        return -1;
    } else if (xVal > yVal) {
        return 1;
    } else {
        return 0;
    }
}

jQuery.fn.dataTableExt.oSort['custom_euro_date-desc'] = function(x, y) {
    var xVal = getCustomEuroDateValue(x);
    var yVal = getCustomEuroDateValue(y);

    if (xVal < yVal) {
        return 1;
    } else if (xVal > yVal) {
        return -1;
    } else {
        return 0;
    }
}

function getCustomEuroDateValue(strDate) {
    var frDatea = $.trim(strDate).split(' ');
    var frTimea = frDatea[1].split(':');
    var frDatea2 = frDatea[0].split('/');
    
    var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]);
    x = x * 1;

    return x;
}

And below is our DataTable initialization.

$("#existingbackups").dataTable({
	"bJQueryUI": true,
	"bFilter": true,
	"bRetrieve":true,
	"bStateSave": true,
	"aoColumns": [
	    {},
	    {},
	    {},
	    { "sType": "custom_euro_date" },
	    null
	]
});

This way, the column sorting for date is supported instead of alphabetical sorting. By the way, here is the date format samples.

24/05/2012 18:59:01
05/06/2012 12:23:16
28/06/2012 17:13:43

Enjoy and share.

2 Comments

2 thoughts on “Custom sorting with jQuery DataTable plugin”

  1. Thank you so much ! It was a lot of time I was looking to resolve a similar problem !!
    🙂

Leave a reply

Your email address will not be published. Required fields are marked *