Search code examples
javascriptjquerysortingtablesorter

Custom alphanumberic sort with jQuery Tablesorter


I'm currently using jQuery Tablesorter for my project's tables, and I want to have it handle a custom sort so that:

A, AA, B, BB, 1, 2

Would sort as:

1, 2, A, B, AA, BB

I'm able to achieve this through the textSorter option during the initialization like so:

                    $(".tablesorter").tablesorter({
                        textSorter: {
                            3: function (a, b) {
                                return b.length > a.length ? -1 : b.length < a.length ? 1 : b.toString() > a.toString() ? -1 : 1;
                            }
                        }
                     }

Or more clearly:

                               if (b.length > a.length) {
                                    return -1;
                                } else if (b.length < a.length) {
                                    return 1;
                                } else {
                                    if (b.toString() > a.toString()) {
                                        return -1;
                                    } else {
                                        return 1;
                                    }
                                }

But what I'd like to do is be able to have this be default sort when a classname is specified, similar to how I'm able to add sorter-floats as a clas to any th like this <th class='sorter-floats'>COL NAME</th> and use the addParser method to handle parsing the value by which to sort like this:

  $.tablesorter.addParser({
      id: "floats",
      is: function (s) {
          return false;
      },
      format: function (s) {
          return $.tablesorter.formatFloat(s.replace(/,/g, ''));
      },
      type: "numeric"
  });

I haven't been able to find any methods in the tablesorter plugin that allow custom sorting in this way. Is this possible, or is the approach I've already used my best option?


Solution

  • Tablesorter wasn't set up to allow the textSorter option to contain anything other than an overall function, or an object containing zero-based column indexes.

    I just updated the master branch with a patch that will also allow adding a column class name (demo):

    $(function() {
    
      $("table").tablesorter({
        theme: 'blue',
        textSorter: {
          '.sorter-float': function(a, b) {
            return b.length > a.length ? -1 :
              b.length < a.length ? 1 :
              b.toString() > a.toString() ? -1 : 1;
          }
        }
      });
    
    });
    

    I haven't decided when the next release will be available, but it won't be too long.