jQuery tablesorter - Not sorting column with formatted currency value

99封情书 提交于 2019-11-29 02:03:31

问题


jQuery 1.7.1 & tablesorter plugin - I have a currency column with thousand separators and values like $52.00 $26.70 $100.00 $50.00 $1,002.00 $1,102.00. When I try to sort getting sorted in the following way,

   $1,002.00  
   $1,102.00
   $26.70
   $50.00
   $52.00
   $100.00

Need values like,

   $26.70
   $50.00
   $52.00
   $100.00
   $1,002.00  
   $1,102.00

Tried many solutions mentioned here, but no success.


回答1:


Tablesorter allows you to define "custom parsers" for things like this.

// add parser through the tablesorter addParser method 
$.tablesorter.addParser({ 
    // set a unique id 
    id: 'thousands',
    is: function(s) { 
        // return false so this parser is not auto detected 
        return false; 
    }, 
    format: function(s) {
        // format your data for normalization 
        return s.replace('$','').replace(/,/g,'');
    }, 
    // set type, either numeric or text 
    type: 'numeric' 
}); 

$(function() {
    $("table").tablesorter({
        headers: {
            6: {//zero-based column index
                sorter:'thousands'
            }
        }
    });
});

You may have to tweak the format function, which I've not tested.




回答2:


If you want to fix all data types (most flexible):

<script type="text/javascript">
    $(function() {
        $("table").tablesorter({
            textExtraction: function(node){ 
                var cell_value = $(node).text();
                var sort_value = $(node).data('value');
                return (sort_value != undefined) ? sort_value : cell_value;
            }
        })
    })
</script>

<td data-value="2008-04-01">01 Apr 2008</td>
<td>Alice</td>
<td data-value="80.00"><span>£80.00</span></td>

This has the advantage of separating display data from the sort data, more reusable.




回答3:


Following the same idea proposed by @Ownen, since TableSorter v2.16.0, you can use the data-text attribute directly, without the need to declare your own textExtraction function (more info here):

<td data-text="2008-04-01">01 Apr 2008</td>
<td>Alice</td>
<td data-text="80.00"><span>£80.00</span></td>

This attribute work with other widgets too, like math.

Note: in order to make it work with the output widget, you need to declare the output_dataAttrib option:

$('#table').tablesorter({
    widgets: ["output"],
    widgetOptions : {
       output_dataAttrib: 'data-text'
    }
});


来源:https://stackoverflow.com/questions/9027438/jquery-tablesorter-not-sorting-column-with-formatted-currency-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!