Formatted Number Sorting With Some Text Data

Formatted Number Sorting With Some Text Data

InershaInersha Posts: 2Questions: 0Answers: 0
edited November 2011 in Plug-ins
Hi there,

I have a simple table with formatted numbers that are being sorted nicely with the formatted numbers plug in. The initial values are grams with 2 decimal points, like this: 15.60g.

However, in some columns there are fields where the text is "n/a", as the numerical data is not available. The formatted numbers sorting plug in has trouble with these columns and will not sort them. You can see an example of this problem in the "sug" column here: http://www.whichprotein.co.uk/protein/whey/nutrition/

Ideally these "n/a" should be sorted to the top (largest values) when the column is sorted. Is there any way I can easily modify the formatted numbers plug in to allow for this, or should I be combining multiple plug ins somehow? Here's the plug in code:

[code]
jQuery.fn.dataTableExt.oSort['formatted-num-asc'] = function(x,y){
x = x.replace(/[^\d\-\.\/]/g,'');
y = y.replace(/[^\d\-\.\/]/g,'');
if(x.indexOf('/')>=0)x = eval(x);
if(y.indexOf('/')>=0)y = eval(y);
return x/1 - y/1;
}
jQuery.fn.dataTableExt.oSort['formatted-num-desc'] = function(x,y){
x = x.replace(/[^\d\-\.\/]/g,'');
y = y.replace(/[^\d\-\.\/]/g,'');
if(x.indexOf('/')>=0)x = eval(x);
if(y.indexOf('/')>=0)y = eval(y);
return y/1 - x/1;
}
[/code]

Thanks in advance!

Replies

  • allanallan Posts: 63,498Questions: 1Answers: 10,470 Site admin
    You could add a check for "if ( x == "n/a" ) { x= 0; }" and the same for y at the top of each function.

    Allan
  • InershaInersha Posts: 2Questions: 0Answers: 0
    Thanks for the tip Allan. I can't seem to get it to work though. The column still doesn't want to sort. Here's the code I'm using:

    [code]
    jQuery.fn.dataTableExt.oSort['formatted-num-asc'] = function(x,y){
    if ( x == "n/a" ) x= 0;
    if ( y == "n/a" ) y= 0;
    x = x.replace(/[^\d\-\.\/]/g,'');
    y = y.replace(/[^\d\-\.\/]/g,'');
    if(x.indexOf('/')>=0)x = eval(x);
    if(y.indexOf('/')>=0)y = eval(y);
    return x/1 - y/1;
    }
    jQuery.fn.dataTableExt.oSort['formatted-num-desc'] = function(x,y){
    if ( x == "n/a" ) x= 0;
    if ( y == "n/a" ) y= 0;
    x = x.replace(/[^\d\-\.\/]/g,'');
    y = y.replace(/[^\d\-\.\/]/g,'');
    if(x.indexOf('/')>=0)x = eval(x);
    if(y.indexOf('/')>=0)y = eval(y);
    return y/1 - x/1;
    }
    [/code]

    I've tried multiple variations of that too. I definitely need to learn more javascript.

    Any ideas where I'm going wrong?
  • allanallan Posts: 63,498Questions: 1Answers: 10,470 Site admin
    Have you set the sType for the column to be "formatted-num"?

    Allan
This discussion has been closed.