Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

  • know to solve this sorting issue?
  • or know the way to disable the sorting on first initiate(display the data as it is coming form db)?

Any suggestions much appreciated.

like image 291
Iladarsda Avatar asked Oct 03 '11 08:10

Iladarsda


Video Answer


1 Answers

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.

like image 182
WTK Avatar answered Sep 22 '22 12:09

WTK