tags:

views:

488

answers:

1

I'm using jquery tablesorter and I'm trying to sort a column with values similar to this:

$100,000 $38,000 ($4,000) $2,000

Data within () are negative numbers. When using the default sort feature, it does not recognize the ($4,000) as a negative number, so I'm trying to create a custom function to handle this.

The solution below is what I have come up with, and it works fine. But I'm wondering if there is a better solution? I'm new to jquery and just looking for some insight.

$(document).ready(function() 
 { 
  $.tablesorter.addParser({
    // set a unique id
    id: 'currency-column',
    is: function(s) {
      // return false so this parser is not auto detected
      return false;
    },
    format: function(s) {
       s = s.replace(/$/g,"");
       s = s.replace(/\(/g,"-");
       s = s.replace(/\)/g,"");
       return $.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9.-]/g),""));
    },

    type: 'numeric'
  });

  $("#myTable").tablesorter({
   headers: {
    3: { sorter:'currency-column' },
    4: { sorter:'currency-column' },
    5: { sorter:'currency-column' },
    6: { sorter:'currency-column' },
    7: { sorter: false },
    10: { sorter:'currency-column' }
   }
  }); 

 } 
);

Again, it does what is required and I'm satisfied with the results (and maybe I should just leave it there...), but if there is a better solution I'd love to hear it.

Thanks

A: 

How abour removing ","

s = s.replace(/,/g,"");

so, your function become:

format: function(s) {
         s = s.replace(/$/g,"");
         s = s.replace(/\(/g,"-");
         s = s.replace(/\)/g,"");
         s = s.replace(/,/g,"");
         return $.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9.-]/g),""));
},

^.^

iyank4