Search code examples
jquerytablesorter

Tablesorter (mottie fork) condinionally multi-column sort


friendly coders :-) I need in rather basic functionality of tablesorter jquery plugin. First of all, I don't need in table pre-sort. I display the table inititally strictly in the order as data are in the file. So, right now my code is VERY simple and is the following one:

<script>
$(document).ready(function() 
{ 
    $("#results").tablesorter({
        cancelSelection: true,
        headers:
            {  0 : { sorter: "text" },
               1 : { sorter: "digit" },
               2 : { sorter: "text" },
               3 : { sorter: "digit" },
               3 : { sortInitialOrder: "desc" },
               4 : { sorter: "digit" },
               4 : { sortInitialOrder: "desc" }
            }
                              });
     } 
); 
    $('#results').on('sortBegin', function () {
         var c = this.config,
         col = c.sortList[0][0];
          if ( col === 0 ) {
// column 0 sorting, add column 2
               c.sortList.push( [2,0] );
   } else if ( col === 2 ) {
// column 2 sorting, add column 4
        c.sortList.push( [4,1] );
    }
}).tablesorter({
    widgets: ['columns']
});
</script>

What I need: 1. sort by column 0 (ascending, default), then column 2 (ascending, default) 2. sort by column 2 (ascending, default), then column 4 (ascending, non-default)

I don't want to use sortAppend because I don't want ALWAYS make some additional sorting. I need in it ONLY for columns 0 and 2. I don't want to use widgets with "secondary" and "thertiary" options because of I don't want to make "secondary" sorting. Really I need in something like conditional sortappend, like

sortAppend [0]: [2,0]
sortAppend [2]: [4,1]

How can I do it?

Upd: I changed the basic question to include the proposed solutions. It's tested and working as required, many thanks to Mottie and his fork of tablesorter!


Solution

  • It's not pretty, but you can bind to the sortBegin event and append the custom sort (demo)

    $(function () {
        $('table').on('sortBegin', function () {
            var c = this.config,
                col = c.sortList[0][0];
            if ( col === 0 ) {
                // column 0 sorting, add column 2
                c.sortList.push( [2,0] );
            } else if ( col === 2 ) {
                // column 2 sorting, add column 4
                c.sortList.push( [4,1] );
            }
        }).tablesorter({
            theme: 'blue',
            widgets: ['zebra', 'columns']
        });
    });