This js code extends the tablesorter plugin in jQuery:
- Parser for sorting values like “$1,300.50″
- Parser for sorting values like “2 months ago”,”3 years ago” (actual timestamp hide in the comment)
- Parser for sorting values like “SMALLER”,”SMALL” (actual text value hide in comment)
- Widget to highlight a row when mouse hovers it
- Widget to highlight a header when mouse hovers it
- Widget to save/memorize sort order via AJAX
Let’s get right into the code:
// add sorting by 1,300,000 (with commas)
$.tablesorter.addParser({
id: “fwnumber”,
is: function(s) {
return false;
},
format: function(s) {
return $.tablesorter.formatFloat(s.replace(/(\,|\%)/g,””));
},
type: “numeric”
});
// only look for value in the comment, eg:
,
$.tablesorter.addParser({
id: “commenttxt”,
is: function(s) {
return /^/.test($.trim(s));
},
format: function(s) {
return s.replace(/^.*/g,”$1″);
},
type: “text”
});
// only look for value in the comment, eg:
$.tablesorter.addParser({
id: “commentnum”,
is: function(s) {
return /^/.test($.trim(s));
},
format: function(s) {
return s.replace(/^.*/g,”$1″);
},
type: “numeric”
});
// show the hover row different than other rows
$.tablesorter.addWidget({
id: “rowHover”,
format: function(table) {
$(“tr:visible”,table.tBodies[0]).hover(
function () { $(this).addClass(table.config.widgetRowHover.css); },
function () { $(this).removeClass(table.config.widgetRowHover.css); }
);
}
});
// apply CSS to the sortable header when mouse hovers it
$.tablesorter.addWidget({
id: “headerHover”,
format: function(table) {
$(“thead th:visible”,table).hover(
function () { if (!table.config.headerList[$(“thead th:visible”,table).index(this)].sortDisabled) $(this).addClass(table.config.widgetHeaderHover.css); },
function () { $(this).removeClass(table.config.widgetHeaderHover.css); }
);
}
});
// call a link via AJAX to save/memorize the sort order
$.tablesorter.addWidget({
id: “memorizeSortOrder”,
format: function(table) {
if (!table.config.widgetMemorizeSortOrder.isBinded) { // only bind if not already binded
table.config.widgetMemorizeSortOrder.isBinded = true;
$(“thead th:visible”,table).click(function() {
var i = $(“thead th:visible”,table).index(this);
$.get(table.config.widgetMemorizeSortOrder.url+i+’|’+table.config.headerList[i].order);
});
} // fi
}
});
Demo HTML file
This table is sortable, click on the headings to sort
Number |
String |
Currency |
Embedded |
Time |
120 |
ABC |
$123.50 |
MEDIUM |
1 month |
0 |
XYZ |
$99 |
SMALL |
1 week |
1 |
Member |
$932,329 |
SMALLER |
2 month |
678 |
John Doe |
$323.23 |
SMALLEST |
1 year |
4,342 |
O’Ryan |
$1,223.50 |
LARGE |
2 day |