Search code examples
javascriptjquerytablesorter

Override table sorter order


I want to override the ordering on tablesorter. Right now I have the following entries in my table that are dynamically added:

1 Active,34 Active, 453 Active, 3235 Active, inactive, inactive

The issue is that there is another column that I want all the Active entries to be sorted by, and not by the number in front of it.

Is it possible to do this with table sorter? if so how?


Solution

  • Ok so I figured it out. What I had to do was use a tablesorter parser. I then use regular expressions to strip the number and spaces off the Active strings. Afterwards I replace inactive with the value of 1, and active, with the value of 2. Then I can sort my table just off the active and inactive category and do further sorting on based of another column. Here is the code below:

    $.tablesorter.addParser({
      //give an id to the parser
      id: 'campaigns',
      is: function(s) {
        return false;
      },
      format: function(s) {
        //remove any numbers and spaces in the string s
        var state = s.replace(/[0-9]/g, '').replace(/\s/g, '');
        //change inactive to a 1 and active to a 2
        return state.toLowerCase().replace(/inactive/,1).replace(/active/,2);
      },
      //sort on a numeric type
      type: 'numeric'
    });
    
    $(function() {
      $("table#game-data-table").tablesorter({
        //sort based off of active inactive, then off column 4,and finally off column 1
        sortList: [[1,1], [3,1], [0,0]],
        headers: {
        1: {
          sorter: 'campaigns'
        }
      }
     });
    });