I love using jQuery tablesorter for quick sorting of my report tables. But sometimes it is not able to sort some of my cells properly. For instance, when I use KPI images to reflect Green, Yellow, and Red states. But it is super easy to extend the tablesorter logic to add custom sort functionality by using the addParser method.
In this example, we will convert our KPI images of Green, Yellow and Red to the following values: 1, 2, 3. That way they will sort Green, Yellow, Red for ascending and Red, Yellow, Green for descending sort.
This defines the custom parser to handle KPI data and assigns it an ID of kpi.
$.tablesorter.addParser({
  // set a unique id
  id: ‘kpi’,
  is: function (s) {
    // return false so this parser is not auto detected
    return false;
    },
  format: function (s) {
    // format your data for normalization
    if (s.toLowerCase().indexOf(“green”) != -1) {
      return 1;
    }
    else if (s.toLowerCase().indexOf(“yellow”) != -1) {
      return 2;
    }
    else if (s.toLowerCase().indexOf(“red”) != -1) {
      return 3;
    }
    else {
      return -1;
    }
  },
  // set type, either numeric or text
  type: ‘numeric’
});
Once the custom parser has been defined, we can tell the tablesorter which column we want to use this logic on. My report table has an id of UnforecastedRevenueSummary.  Also, I have to add a text extraction item here.  Otherwise, the tablesorter tends to ignore markup and would not be able to sort on what is contained in an image.
$(“#UnforecastedRevenueSummary”).tablesorter({
  // text extraction to handle image, otherwise markup tends to be ignored
   textExtraction:function(s){
var $el = $(s),
$img = $e1.find(‘img’);
return $img.length ? $img[0].src : $e1.text();
},
 
  // here i am assigning the default sort
  sortList: [[1, 0], [2, 0], [3, 0]],
  // here i am stating that the very first column will use the custom kpi sort (columns contain a zero index)
  headers: {
    0: {
      sorter: ‘kpi’
    }
  }
});
<tableid=”UnforecastedRevenueSummary”class=”report tablesorter”style=”table-layout:fixed;”>
. . .
</table>
Advertisements