Search code examples
javascriptjquerytablesorter

tablesorter.js multiple textExtraction


Using tablesorter.js to sort table columns.

I have one column with images, so I used textExtraction to get image alt value to do sorting.

Now I want to use textExtraction to sort other columns with commas and currency symbols.

Independently, both will work but I am not able to get both of them working.

Tablesorter has an example that I am not able to adapt.

textExtraction: {
  0: function(node, table, cellIndex){ return $(node).find("strong").text(); },
  1: function(node, table, cellIndex){ return $(node).find("div").text(); },
  2: function(node, table, cellIndex){ return $(node).find("span").text(); },
  3: function(node, table, cellIndex){ return $(node).find("em").text(); },
  4: function(node, table, cellIndex){ return $(node).find("a").text(); },
  '.date' : function(node, table, cellIndex){ return $(node).find("u").text(); }
}

I modified my code as follows:

$(document).ready(function($){ 
    $("#cardSort").tablesorter(
        {
            initWidgets: true,

            textExtraction: {
                0: function(s){
                    if($(s).find('img').length == 0) return $(s).text();
                    return $(s).find('img').attr('alt');
                },
                1: function(s){
                    return $(s).text().replace(/[,$£€]/g,'');
                }                    
            }
        }
    );
}
); 

This appears to be same as the tablesorter example eg it is using the numbered function method. But in this format neither work.

Any ideas on how to have both textExtraction functions?

Edit to add: this is TableSorter Version 2.0.5b


Solution

  • It sounds like you might still be using the original version of tablesorter (v2.0.5)... setting the textExtraction as an object doesn't work on that version, you'll need to use my fork of tablesorter.


    Update: If you must use v2.0.5, then try the following:

    textExtraction: function(node) {
      var $cell = $(node),
        text = $cell.text();
      switch(node.cellIndex) {
        case 0:
          return $cell.find('img').length ? $cell.find('img').attr('alt') : text;
        case 1:
          return text.replace(/[,$£€]/g,'');
        default:
          return text;
      }
    }
    

    Note: This method won't work as expected when there are colspans within the tbody.