Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery tablesorter - Not sorting column with formatted currency value

Tags:

jQuery 1.7.1 & tablesorter plugin - I have a currency column with thousand separators and values like $52.00 $26.70 $100.00 $50.00 $1,002.00 $1,102.00. When I try to sort getting sorted in the following way,

   $1,002.00      $1,102.00    $26.70    $50.00    $52.00    $100.00 

Need values like,

   $26.70    $50.00    $52.00    $100.00    $1,002.00      $1,102.00 

Tried many solutions mentioned here, but no success.

like image 202
SyAu Avatar asked Jan 27 '12 00:01

SyAu


2 Answers

Tablesorter allows you to define "custom parsers" for things like this.

// add parser through the tablesorter addParser method  $.tablesorter.addParser({      // set a unique id      id: 'thousands',     is: function(s) {          // return false so this parser is not auto detected          return false;      },      format: function(s) {         // format your data for normalization          return s.replace('$','').replace(/,/g,'');     },      // set type, either numeric or text      type: 'numeric'  });   $(function() {     $("table").tablesorter({         headers: {             6: {//zero-based column index                 sorter:'thousands'             }         }     }); }); 

You may have to tweak the format function, which I've not tested.

like image 112
Beetroot-Beetroot Avatar answered Oct 21 '22 11:10

Beetroot-Beetroot


If you just want to fix currency numbers (quickest):

<script type="text/javascript">     $("table").tablesorter({         textExtraction: function(node){              // for numbers formattted like €1.000,50 e.g. Italian             // return $(node).text().replace(/[.$£€]/g,'').replace(/,/g,'.');              // for numbers formattted like $1,000.50 e.g. English             return $(node).text().replace(/[,$£€]/g,'');          }     }) </script>  <td><span>£80,000.00</span></td> 

I don't like these 3 other proposed solutions on StackOverflow:

  1. 'Use custom parser and apply in the table sort init' - not reusable for lots tables
  2. 'Use custom parser and apply with table cell's class' - dirty markup
  3. 'Fix TableSorters currency sort in source' - hassle for future upgrades
like image 28
Owen Avatar answered Oct 21 '22 10:10

Owen