Search code examples
jquerysortingtablesorter

How do I make the jQuery table sorter always initially sort on the last column?


I'm using the JQuery tablesorter v 2.0. I currently have it set up like so

$("#myTable").tablesorter({
    sortList: [[4,0]]
}); 

but how would I set up the default sort order to always be the last column in the table? The reason hard-coding a number may not be ideal is because I'm dynamically generating the table data and sometime the table will have five columns and sometime it will have six.


Solution

  • You could count the number of headers in your table and use that to get the last column index. For example:

    // Get the number of "th" within the first "tr":
    var columnCount = $('table tr:first').children('th').length;
    
    $("#myTable").tablesorter({
        sortList: [[columnCount - 1, 0]]
    });