Reputation: 395
I'm trying to format some data of a table that is constantly updated by ajax
.
I want that the float data become this
1.100.500,00 (currency)
after I sort it.
The problem is that tablesorter
only sorts the float values correctly if they are in the first format. What I need to do is:
ajax
loads the data, show it like (currency), as currency.table <th>
is clicked to sort data, remove the (currency) currency format and sort the data correctly.I already tried this:( that I've found that it's the solution to many questions here in SO)
$.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'
});
$("#table_1").tablesorter({
headers: {
2: {//zero-based column index
sorter:'thousands'
}
}
});
but it's not working.
Upvotes: 1
Views: 375
Reputation: 86433
There are four things that fixing (demo):
.replace(/\./g, "")
(the period needs to be escaped as well).$
from the string,
with a decimal point, so the value gets parsed correctly.Convert the value from a string to a number using the built-in $.tablesorter.formatFloat
function.
$.tablesorter.addParser({
id: 'thousands',
is: function(s) {
return false;
},
format: function(s) {
var number = s.replace(/\$/g, '').replace(/\./g, '').replace(/,/g, '.');
return $.tablesorter.formatFloat(number);
},
type: 'numeric'
});
$(function() {
$("table").tablesorter({
theme: 'blue',
headers: {
0: {
sorter: 'thousands'
}
}
});
});
The demo I shared is using my fork of tablesorter, but the code will also work as expected in the original version.
Upvotes: 1