Reputation: 45
I'm using the jQuery tablesorter plugin and I'd like to make my table more readable by using a comma delimiter on the thousands, i.e. number_format($value, 0, " ", ",");
However, this disrupts the sorting. I've been searching for a solution (e.g. http://lab.christianmontoya.com/jquery-tablesort-numbers-commas/), but I haven't managed to adjust it and accommodate my table. I'm new to scripting, so please be indulgent.
What should my javascript block look like?
<head>
<script type="text/javascript">
$(document).ready(function() {
$("#myTable").tablesorter( {
sortList: [[1,1], [2,1]],
widgets: ['zebra'],
} );
});
</script>
</head>
<body>
<table id="myTable" class="tablesorter">
<thead>
<tr>
<th>Username</th>
<th>Level</th>
<th>Experience</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fiery</td>
<td><?php echo number_format(2400, 0, " ", ","); ?></td>
<td><?php echo number_format(378433689, 0, " ", ",");?></td>
</tr>
<tr>
<td>Sixten</td>
<td><?php echo number_format(1600, 0, " ", ","); ?></td>
<td><?php echo number_format(1000000000, 0, " ", ",");?></td>
</tr>
<tr>
<td>Penny</td>
<td><?php echo number_format(885, 0, " ", ","); ?></td>
<td><?php echo number_format(8900002, 0, " ", ","); ?></td>
</tr>
<tr>
<td>Petra</td>
<td><?php echo number_format(2400, 0, " ", ","); ?></td>
<td><?php echo number_format(398433889, 0, " ", ","); ?></td>
</tr>
<tr>
<td>Neu</td>
<td><?php echo number_format(4974, 0, " ", ","); ?></td>
<td><?php echo number_format(198433889, 0, " ", ","); ?></td>
</tr>
</tbody>
</table>
</body>
Upvotes: 4
Views: 3052
Reputation: 17380
You need to apply your custom format to the header/column you want:
Markup:
<table id="myTable" class="tablesorter" border="0" cellpadding="0" cellspacing="1">
<thead>
<tr>
<th>
Price
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
1,000.00
</td>
</tr>
<tr>
<td>
100,100.00
</td>
</tr>
<tr>
<td>
100,980.00
</td>
</tr>
<tr>
<td>
100,122.00
</td>
</tr>
<tr>
<td>
120,122.00
</td>
</tr>
<tr>
<td>
540,122.00
</td>
</tr>
<tr>
<td>
222,122.00
</td>
</tr>
<tr>
<td>
100,020.00
</td>
</tr>
<tr>
<td>
100,251.00
</td>
</tr>
<tr>
<td>
100,364.00
</td>
</tr>
<tr>
<td>
300,122.00
</td>
</tr>
</tbody>
</table>
jQuery:
$(document).ready(function () {
jQuery.tablesorter.addParser({
id: "fancyNumber",
is: function (s) {
return /^[0-9]?[0-9,\.]*$/.test(s);
},
format: function (s) {
return jQuery.tablesorter.formatFloat(s.replace(/,/g, ''));
},
type: "numeric"
});
$("#myTable").tablesorter({
headers: { 0: { sorter: 'fancyNumber'} },
widgets: ['zebra']
});
});
JSFiddle: http://jsfiddle.net/eAgDC/
Upvotes: 6