Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simply sort by the last column of datatable

I'm really really new to dataTable, and I just need one simple solution:

var initBasicTable = function() {

    var table = $('#basicTable');

    var settings = {
        "sDom": "t",
        "sPaginationType": "bootstrap",
        "destroy": true,
        "paging": false,
        "scrollCollapse": true,
        "order": [[0,'desc']]
    };

    table.dataTable(settings);
    $('#basicTable input[type=checkbox]').click(function() {
        if ($(this).is(':checked')) {
            $(this).closest('tr').addClass('selected');
        } else {
            $(this).closest('tr').removeClass('selected');
        }

    });

}

This is working, for sorting the first column by default.

But I read that changing the 0 in "order": [[0,'desc']] into negative number will begin sorting from the columns on the right. However this:

var settings = {
        "sDom": "t",
        "sPaginationType": "bootstrap",
        "destroy": true,
        "paging": false,
        "scrollCollapse": true,
        "order": [[-1,'desc']]
};

Throws an error and I have no idea where to continue.

I know dataTable is really powerful and that but, this is no what I was looking for but plenty already

Nothing for 'Sort by last(-1) column'? I felt lost. anyone?

like image 411
Fan Zhang Avatar asked Aug 03 '15 13:08

Fan Zhang


People also ask

How do I sort a specific column 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.

How do you sort DataTables with date in descending order?

I use the following code and it works for me: $('#tableid'). DataTable({ "order": [[, 'desc']],//order column in descending order. "columnDefs": [ { "type": "date", "targets": }//date column formatted like "03/23/2018 10:25:13 AM". ], "pageLength": 25 });


1 Answers

It turned out not so hard, with a bit of work around:

var table = $('#basicTable');
    var index = $(table).find('th:last').index();
    var settings = {
        "sDom": "t",
        "sPaginationType": "bootstrap",
        "destroy": true,
        "paging": false,
        "scrollCollapse": true,
        "order": [
            [index, "desc"]
        ]
    };

This will get the index of the last 'column' and sort on it first. Thanks for the help guys.

like image 182
Fan Zhang Avatar answered Nov 09 '22 07:11

Fan Zhang