jQuery DataTables: how to sort by custom parameter

2019-07-05 05:30发布

问题:

I have a pretty common use case where I show the formatted price in a Price column, eg. "20,000.00". So when I try to sort it, it treats it as a string and doesn't sort well:

  • 10.00
  • 20,000.00
  • 5,000.00

Can I make it so that it would sort by the data- parameter value, which would be non-formatted float number?

And related to this question: how do you disable sorting for the given column? I'm using DataTables 1.9.4.

回答1:

To answer your first question, you could use the Formatted Numbers plugin available on the DataTables plugin page. I would post the code here, but since they update often, I'll just post the link instead.

http://datatables.net/plug-ins/type-detection

You have a couple of options for disabling sorting on a particular column. You could take the legacy route and put a line in your init object such as...

"aoColumns": [
   null,null,null,{ "bSortable": false },null,null
]

Where null is a column you don't want to do anything to, and the bSortable object is the column you want to effect.

Since you are running 1.9+, you can do the following.

"aoColumnDefs": [
    { "bSortable": false, "aTargets": [ 4 ] }
],

In this example, 4 is the column you want to disable sorting on. Remember, the first column is 0, so this would technically be the 5th column.



回答2:

Use this page http://datatables.net/plug-ins/sorting to see all the sorting types you can add. There are quite a few out there and are easy to use. Basically you need to include the piece of code that it shows under the show details section of each type. This code needs to be included after datatables has initialized. Personally since I have quite a few that I use across my site, I have made a separate file called datatables.sorting.js and I include that after I include datatables. This way I can add as many of the various sorting types as needed.

After you add the code, you can use the aoColumns parameter to tell datatables to apply that sorting method on whichever column you want:

$('#myTable').dataTable({
"aoColumns": [
            null,
            null,
            { "sType": "formatted-num" }
        ]
});

http://jsfiddle.net/davidstetler/5Z8fZ/

I added the code for sorting formatted numbers which you can include like I did, or you can include in a separate file.