Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple custom sorting function for jQuery DataTables

Numeric sorting is not working on my dataset. So I made a custom sorting that converts whole string into number then sorts based on that, but for some reasons its not working. What am i missing here?

$.fn.dataTableExt.oSort["test-desc"] = function (x, y)
{

         x = parseInt(x);
        y = parseInt(y);

        if ( x < y)
        {
            return 1;
        }

        return 0;


};

$.fn.dataTableExt.oSort["test-asc"] = function (x, y)
{

    x = parseInt(x);
    y = parseInt(y);

    if ( x > y)
    {
        return 1;
    }

    return 0;

}

$('table').DataTable({
    "pageLength": 300,
    "bLengthChange": false,
    "columnDefs": [
    { "type": "test", targets: 3 }
    ]
});

enter image description here

Both ascending and descending are not working properly. I have checked these functions are being called and properly converting strings to numeric instances.

like image 361
Waleed Avatar asked Nov 25 '25 22:11

Waleed


1 Answers

jQuery DataTable sort function doesn't return 1 and 0. Instead they return 1 and -1. So modifying the sort function made them work perfectly.

    $.fn.dataTableExt.oSort["test-desc"] = function (x, y)
    {

        x = parseInt(x);
        y = parseInt(y);

        if ( x > y)
        {
            return -1;
        }

        return 1;

    };

    $.fn.dataTableExt.oSort["test-asc"] = function (x, y)
    {

        x = parseInt(x);
        y = parseInt(y);

        if ( x > y)
        {
            return 1;
        }

        return -1;
    }
like image 166
Waleed Avatar answered Nov 27 '25 13:11

Waleed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!