jcvd
jcvd

Reputation: 443

jquery tablesorter textExtraction

I am using the jquery tablesorter plugin

webpage is here: http://redbluffbullsale.com/bulls-listings

I have a complex textExtraction function defined below:

var jgExtraction = function(node) {
  if (node.childNodes[0].length > 0) {
    return node.childNodes[0].innerHTML;
  } else {
    return node.innerHTML;
  }
}

jQuery('#bullsTable').tablesorter({
  textExtraction: 'jgExtraction',
  headers: {
    0 : {sorter: false},
    13: {sorter: 'digit'},
    14: {sorter: 'digit'}
  }
});

In a few of the columns (13 & 14) there is data that can be in the following format:

number (ex: 0.9, 2.3, 4, -2, -2.5, etc) text (the letter I) plus number (I+2.3, I-0.9, I+1.4, etc) plus sign with number (+2.4, +3.1, +0.9, etc)

On the server I am controlling the column data so that if it is a number or a negative number it is dumped in the <td>, but if the column data has an I+, I-, or a +, then that the column has the I+, I- or + separated from the number with <span> tags, like:

<td>-1.4</td>
<td>I+<span>1.6</span></td>
<td>I-<span>3.4</span></td>
<td>+<span>2.2</span></td>

My jgExtraction should return the innerHTML if there is no span child node, or return the contents of the childNode[0] (span) if it exists. The sorting is not working for the columns with I+ or I-. You can see what is wrong by checking out the URL above.

What am I doing wrong?

Upvotes: 0

Views: 3462

Answers (1)

Mottie
Mottie

Reputation: 86443

There are a few problems in the above code.

  • The name of the text extraction function shouldn't be added as a string

    textExtraction: 'jgExtraction', // wrong
    textExtraction: jgExtraction,   // correct
    
  • Within the jgExtraction function, check the length of child nodes, not the length of the first item

    if (node.childNodes[0].length > 0) { // wrong 
    if (node.childNodes.length > 1) {    // correct
    
  • A text node will return undefined when checking its innerHTML. It should be targetting the span anyway:

    return node.childNodes[0].innerHTML // wrong
    return node.childNodes[1].innerHTML; // target the span
    

Here is the modified code & a demo:

var jgExtraction = function(node) {
    if (node.childNodes.length > 1) {
        return node.childNodes[1].innerHTML;
    } else {
        return node.innerHTML;
    }
}

If you are interested, I have a fork of tablesorter which will allow you to sort empty table cells to the top, bottom or treat them as having a value of zero (the default behavior) - see this demo

Upvotes: 2

Related Questions