Pradeep
Pradeep

Reputation: 803

Custom column sorting in jquery Datatable

I am using jquery datatable to display data. I display '--' when there is no data. Currently when the table sorts the data all the '--' comes in the beginning and the order looks like below:

--
--
10
20
400
800

But I need to make '--' to be displayed last when sorted in ascending order and should look something like below:

10
20
400
800
--
--

Please let me know how can we get this behavior in jquery datatable?

Upvotes: 0

Views: 795

Answers (2)

user3401335
user3401335

Reputation: 2405

you can use an exstension

jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "myorder-pre": function (a) {

    },

    "myorder-asc": function (a, b) {
        if(a == '--' && b != '--')
            return 1;
        else if(b == '--' && a != '--')
            return -1;
        else if(b == '--'&& a == '--')
            return 0;
        else
        {
            a = parseFloat(a);
            b = parseFloat(b);
            return ((a < b) ? -1 : ((a > b) ? 1 : 0));

        }
    },

    "myorder-desc": function (a, b) {
        if(a == '--' && b != '--')
            return -1;
        else if(b == '--' && a != '--')
            return 1;
        else if(b == '--'&& a == '--')
            return 0;
        else
        {
            a = parseFloat(a);
            b = parseFloat(b);
            return ((a < b) ? 1 : ((a > b) ? -1 : 0));

        }
    }
});

myorder-pre is used before all the order call. myorder-asc when you order asc. Return number negative if a minor b, positive if a major b, 0 if equal. Desc work adverse

then in the definition of columns of datatable, use

"aoColumnDefs": [{ "sType": 'myorder'}]

Upvotes: 1

Hamid Narikkoden
Hamid Narikkoden

Reputation: 861

You can make use of the following code :

 $('#example').dataTable( {
    "aaSorting": [[ 4, "desc" ]]
} );

For the reference

Upvotes: 0

Related Questions