views:

434

answers:

2

I'm trying to write a custom parser for the jQuery plugin, Tablesorter. The idea is for it to sort the numbers in descending order on the first click.

However, when I sort the table, the order doesn't change. Sometimes a few rows move, but most of them stay the same. Here is the code:

$.tablesorter.addParser({
 id: 'desc',
 is: function(s) { return false },
 format: function(s) {
  return 1.0 / parseFloat( s.replace(/,/g,'') );
 },
 type: 'numeric'
});

The other parsers I've written are working fine. I tried 9999 minus the number instead of 1.0 divided by it, in case it was a problem with floats (no luck).

A: 

To sort something in reverse numeric order, to me the natural way to go is to multiply it by -1, rather than the methods you've tried.

As to the parser itself, the only difference I notice is that you are returning an actual number, whereas the parser example at the Tablesorter site returns a string. Perhaps converting the value back to string before returning it would work?

Adam Bellaire
Isn't it returning a number? `replace(/bad/,0)` would return 0, rather than "0", right?
DisgruntledGoat
No, `replace` always returns a string. You need to use parseInt, as you did in the solution that you posted a moment ago.
Adam Bellaire
+2  A: 

I found a solution. I had some empty cells in each column, which were being parsed as "NaN". Why this screwed up the ordering, I don't know (blank cells were intermittently spaced with regular numbers, there was no order to anything).

In short, this code works for the format function:

 format: function(s) {
  if ( s == '' )
   return 0;  
  return -parseInt( s.replace(/,/g,'') );
 }
DisgruntledGoat
Good catch with the empty fields. Didn't even consider that possibility reading your OP.
Adam Bellaire