Search code examples
jquerytablesorter

mottie tablesorter: force sortText (NOT sortNatural)


I've made a custom parser like so:

    $.tablesorter.addParser({
        id: 'custom-sort-value',
        is: function(s) {
            // return false so this parser is not auto detected
            return false;
        },
        format: function(s, table, cell, cellIndex) {
            return $(cell).data('sort-value').toString();
        },
        type: 'text'
    });

However, I've noticed it ends up using the tablesorter function sortNatural (because of type: 'text'). However, I need it to just do a basic alphabetical sort, like tablesorter's sortText (I can't have it split the strings and compare each split). Is there a way I can force it to do this?


Solution

  • So, you don't need a custom parser to grab text from an attribute. The fork of tablesorter attempts to get a custom sort string from data-text (which can be modified by the textAttribute option), but only when the textExtraction option is set to "basic" (default setting).

    So, to use the basic sortText sort, use the textSorter option to set your custom sort function by column:

    $(function(){
      $("table").tablesorter({
        textSorter : {
          // replace INDIVIDUAL COLUMN text sorter functions
          0 : function(a, b, direction, columnIndex, table){
            // same as $.tablesorter.sortText (basic alphabetical sort)
            // direction: true = ascending; false = descending
            // columnIndex: zero-based index of the current table column being sorted
            // table: table DOM element (access options by using table.config)
            return a > b ? 1 : (a < b ? -1 : 0);
          },
          1 : $.tablesorter.sortText,    // same as the function in column 0 above (modified in v2.12)
          2 : $.tablesorter.sortNatural, // renamed v2.12 from $.tablesorter.sortText - performs natural sort
          3 : Array.AlphanumericSort     // alphanumeric sort from sugar (http://sugarjs.com/arrays#sorting)
        }
      });
    });