Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to impose numerical sort with jQuery and dataTables?

I am using the DataTables jQuery plugin. I am trying to enable sort interaction, but when sorting it sorts alphabetically and not numerically. As you can see in the enclosed picture, -4317.93 is shown after -631 and -456. How can I make DataTable sort a column numerically?

Example

like image 610
Spredzy Avatar asked Nov 04 '11 11:11

Spredzy


People also ask

What is bDestroy in DataTable?

bDestroy. Show details. Replace a DataTable which matches the given selector and replace it with one which has the properties of the new initialisation object passed. If no table matches the selector, then the new DataTable will be constructed as per normal.

How do you sort a number in a DataTable?

Using the order initialisation parameter, you can set the table to display the data in exactly the order that you want. The order parameter is an array of arrays where the first value of the inner array is the column to order on, and the second is 'asc' (ascending ordering) or 'desc' (descending ordering) as required.

What is jQuery DataTables JS?

jQuery DataTable is a powerful and smart HTML table enhancing plugin provided by jQuery JavaScript library. It is a highly flexible tool that is basically created to display information in tables as well as adding interactions to them, hence, enhancing data accessibility in HTML tables.


1 Answers

Updated answer

With the latest version of DataTables you need to set the type property of the object you provide in the columnDefs array, like this:

$('#example').dataTable({
  "columnDefs": [
    { "type": "num" }
  ]
});

Note that there are many other methods of sorting which can be found in the documentation


Original answer

You need to add the sType parameter to your column definition.

For example:

$('#example').dataTable({
  "aoColumnDefs": [
    { "sType": "numeric" }
  ]
});

More information in the DataTable documentation: http://www.datatables.net/plug-ins/sorting

like image 95
Rory McCrossan Avatar answered Oct 29 '22 10:10

Rory McCrossan