Search code examples
javascriptjquerytablesorter

jQuery Table sorter Sorting of Float distance


I am using tablesorter to sort the table content. My table is as below.

<table class="results" border="1">
<thead>
    <tr>
        <th class="header">No</th> 
        <th class="header">Distance</th>
        <th class="header">Diagnostic Fee</th>
        <th class="header">Regular Price </th>
        <th class="header">Company Price</th>
        <th class="">&nbsp;</th>
    </tr>
</thead>

<tbody>
    <tr>
        <td>1</td>
        <td class="distance"><a>16.50 kms.</a></td>
        <td class="brand"><a>Credited</a></td>
        <td><a>$5</a></td>
        <td><a>$5<small>after 5% cash back</small></a></td>
    </tr>
    <tr>
           <td>2</td>
        <td class="distance"><a>6.30 kms.</a></td>
        <td class="brand"><a>Credited</a></td>
        <td><a>$8</a></td>
        <td><a>$8<small>after 5% cash back</small></a></td>
    </tr>
    <tr>
        <td>3</td> 
        <td class="distance"><a>10.25 kms.</a></td>
        <td class="brand"><a>Credited</a></td>
        <td><a>$2</a></td>
        <td><a>$2<small>after 5% cash back</small></a></td>
    </tr>
</tbody>
</table>​

I want to sort the table using distance and price. I am facing difficulty is solving table with distance, because distance is displayed in alphanumeric like "12 kms". So, The table is not getting sorted.

Can anyone advise how to parse the content by taking only digits?

here is the jsfiddle demo


Solution

  • Tablesorte has an option 'textExtraction', so you can define a function to go through the text before sorting. Example:

    $("table").tablesorter({
            debug:false,  
            sortList: [[0, 0], [2, 0]],
            textExtraction: function(node) {  
                var $node = $(node)
                var text = $node.text();
                if ($node.hasClass('distance')) {
                    text = text.replace('kms', '');
                };
    
                return text;
            }
    });
    

    Updated fiddle