Iladarsda
Iladarsda

Reputation: 10696

jQuery - datatable plugin - sorting issue

I'm using DataTables plugin from http://datatables.net.
The plugin it self is very useful,but I have a big of a problem with it.

It is return a list of address for some searches in the following format.

1 Main Street
12 Main Street
13 Main Street
14 Main Street
...
2 Main Street
3 Main Street
4 Main Street
5  Main Street
..

As you can see the sorting is not what I would expected. Will return all numbers starting with 1 eg, 11, 111, 1111 before 2.

Have any of you have some expirience with the plugin?

Any suggestions much appreciated.

Upvotes: 5

Views: 6847

Answers (2)

WTK
WTK

Reputation: 16971

To solve this particular issue you can use natural-sort plugin for datatables. Read all about it at http://datatables.net/plug-ins/sorting (search for "Natural sorting").

In short, provided you've downloaded and embedded naturalSort function, you then define sort handle for datatables like this:

jQuery.fn.dataTableExt.oSort['natural-asc']  = function(a,b) {
    return naturalSort(a,b);
};

jQuery.fn.dataTableExt.oSort['natural-desc'] = function(a,b) {
    return naturalSort(a,b) * -1;
};

You also need to specify the sSortDataType parameter for the column, to tell it which plug-in function to use (in example below I set the sorting to natural for the third column of my table):

$('#example').dataTable( {
    "aoColumns": [
        null,
        null,
        { "sType": "natural" }
]
});

Here's working fiddle http://jsfiddle.net/zhx32/14/

Note: it seems that you, in fact, number of elements on "aoColumns" have to be equal to number of columns in the table, otherwise you'll get an error. Null value indicates that datatables plugin should use default sort method for that column.

Upvotes: 4

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

You should use a sorting plugin for that something like this:

jQuery.fn.dataTableExt.oSort['num-html-asc']  = function(a,b) {
    var x = a.replace( /<.*?>/g, "" );
    var y = b.replace( /<.*?>/g, "" );
    x = parseFloat( x );
    y = parseFloat( y );
    return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
    var x = a.replace( /<.*?>/g, "" );
    var y = b.replace( /<.*?>/g, "" );
    x = parseFloat( x );
    y = parseFloat( y );
    return ((x < y) ?  1 : ((x > y) ? -1 : 0));
};

and then specify that type in aoColumns

        "aoColumns": [
            null,
            null,
            null,
            { "sType": "num-html" },
            null
        ]

Upvotes: 3

Related Questions