Search code examples
javascriptjquerysortingtablesorter

Tablesorter - sort by td class


I am trying to use tablesorter to sort a column by class. The class will determine the background image to indicate true/false.

The two types of class within the column will be:

<td class='icon silk-cross'>
<td class='icon silk-tick'>

I've tried this code as a custom parser but have not come up with a working solution.

  $.tablesorter.addParser({
    id: 'truefalse',
    is: function(s) {
      return false;
    },
    format: function(s, table, cell) {
      var $cell = $(cell);
      return $cell.attr('class') || s;
    },
    type: 'text'
  });

Is there a way to access the attributes of each cell?

EDIT: jsfiddle at http://jsfiddle.net/LtyMN/


Solution

  • You just need to include the new parser in the headers option (demo):

    $.tablesorter.addParser({
        id: 'truefalse',
        is: function (s) {
            return false;
        },
        format: function (s, table, cell) {
            var $cell = $(cell);
            return $cell.attr('class') || s;
        },
        type: 'text'
    });
    
    $("table").tablesorter({
        headers : {
            2: { sorter: 'truefalse' }
        },
        widgets: ['zebra']
    });
    

    Please note that if you use the updateCell method, it won't provide the cell argument properly to the parser format function. I have fixed this issue in my fork of tablesorter.