3 * TableSorter 2.0 - Client-side table sorting with ease!
\r
5 * @requires jQuery v1.1.3
\r
7 * Copyright (c) 2007 Christian Bach
\r
8 * Examples and docs at: http://tablesorter.com
\r
9 * Dual licensed under the MIT and GPL licenses:
\r
10 * http://www.opensource.org/licenses/mit-license.php
\r
11 * http://www.gnu.org/licenses/gpl.html
\r
16 * @description Create a sortable table with multi-column sorting capabilitys
\r
18 * @example $('#table').tablesorter();
\r
19 * @desc Create a simple tablesorter interface.
\r
21 * @example $('#table').tablesorter({ sortList:[[0,0],[1,0]] });
\r
22 * @desc Create a tablesorter interface and sort on the first and secound column in ascending order.
\r
24 * @example $('#table').tablesorter({ headers: { 0: { sorter: false}, 1: {sorter: false} } });
\r
25 * @desc Create a tablesorter interface and disableing the first and secound column headers.
\r
27 * @example $('#table').tablesorter({ 0: {sorter:"integer"}, 1: {sorter:"currency"} });
\r
28 * @desc Create a tablesorter interface and set a column parser for the first and secound column.
\r
31 * @param Object settings An object literal containing key/value pairs to provide optional settings.
\r
33 * @option String cssHeader (optional) A string of the class name to be appended to sortable tr elements in the thead of the table.
\r
34 * Default value: "header"
\r
36 * @option String cssAsc (optional) A string of the class name to be appended to sortable tr elements in the thead on a ascending sort.
\r
37 * Default value: "headerSortUp"
\r
39 * @option String cssDesc (optional) A string of the class name to be appended to sortable tr elements in the thead on a descending sort.
\r
40 * Default value: "headerSortDown"
\r
42 * @option String sortInitialOrder (optional) A string of the inital sorting order can be asc or desc.
\r
43 * Default value: "asc"
\r
45 * @option String sortMultisortKey (optional) A string of the multi-column sort key.
\r
46 * Default value: "shiftKey"
\r
48 * @option String textExtraction (optional) A string of the text-extraction method to use.
\r
49 * For complex html structures inside td cell set this option to "complex",
\r
50 * on large tables the complex option can be slow.
\r
51 * Default value: "simple"
\r
53 * @option Object headers (optional) An array containing the forces sorting rules.
\r
54 * This option let's you specify a default sorting rule.
\r
55 * Default value: null
\r
57 * @option Array sortList (optional) An array containing the forces sorting rules.
\r
58 * This option let's you specify a default sorting rule.
\r
59 * Default value: null
\r
61 * @option Array sortForce (optional) An array containing the forces sorting rules.
\r
62 * This option let's you specify a default sorting rule.
\r
63 * Default value: null
\r
66 * @option Boolean widthFixed (optional) Boolean flag indicating if tablesorter should apply fixed widths to the table columns.
\r
67 * This is usefull when using the pager companion plugin.
\r
68 * This options requires the dimension jquery plugin.
\r
69 * Default value: false
\r
71 * @option Boolean cancelSelection (optional) Boolean flag indicating if tablesorter should cancel selection of the table headers text.
\r
72 * Default value: true
\r
78 * @cat Plugins/Tablesorter
\r
80 * @author Christian Bach/christian.bach@polyester.se
\r
85 tablesorter: new function() {
\r
87 var parsers = [], widgets = [];
\r
90 cssHeader: "header",
\r
91 cssAsc: "headerSortUp",
\r
92 cssDesc: "headerSortDown",
\r
93 sortInitialOrder: "asc",
\r
94 sortMultiSortKey: "shiftKey",
\r
96 textExtraction: "simple",
\r
99 widgetZebra: {css: ["even","odd"]},
\r
102 cancelSelection: true,
\r
109 /* debuging utils */
\r
110 function benchmark(label,stamp) {
\r
111 log(label + "," + (new Date().getTime() - stamp.getTime()) + "ms");
\r
115 if (typeof console != "undefined" && typeof console.debug != "undefined") {
\r
122 /* parsers utils */
\r
123 function buildParserCache(table,$headers) {
\r
125 if(table.config.debug) { var parsersDebug = ""; }
\r
127 var list = [], cells = table.tBodies[0].rows[0].cells, l = cells.length;
\r
129 for (var i=0;i < l; i++) {
\r
132 if($.meta && ($($headers[i]).data() && $($headers[i]).data().sorter) ) {
\r
134 p = getParserById($($headers[i]).data().sorter);
\r
136 } else if((table.config.headers[i] && table.config.headers[i].sorter)) {
\r
138 p = getParserById(table.config.headers[i].sorter);
\r
141 p = detectParserForColumn(table.config,cells[i]);
\r
144 if(table.config.debug) { parsersDebug += "column:" + i + " parser:" +p.id + "\n"; }
\r
149 if(table.config.debug) { log(parsersDebug); }
\r
154 function detectParserForColumn(config,node) {
\r
155 var l = parsers.length;
\r
156 for(var i=1; i < l; i++) {
\r
157 if(parsers[i].is($.trim(getElementText(config,node)))) {
\r
162 // 0 is always the generic parser (text)
\r
166 function getParserById(name) {
\r
167 var l = parsers.length;
\r
168 for(var i=0; i < l; i++) {
\r
169 if(parsers[i].id.toLowerCase() == name.toLowerCase()) {
\r
177 function buildCache(table) {
\r
179 if(table.config.debug) { var cacheTime = new Date(); }
\r
181 var totalRows = (table.tBodies[0] && table.tBodies[0].rows.length) || 0,
\r
182 totalCells = table.tBodies[0].rows[0].cells.length,
\r
183 parsers = table.config.parsers,
\r
184 cache = {row: [], normalized: []};
\r
186 for (var i=0;i < totalRows; ++i) {
\r
188 /** Add the table data to main data array */
\r
189 var c = table.tBodies[0].rows[i], cols = [];
\r
191 cache.row.push($(c));
\r
193 for(var j=0; j < totalCells; ++j) {
\r
194 cols.push(parsers[j].format(getElementText(table.config,c.cells[j]),table,c.cells[j]));
\r
197 cols.push(i); // add position for rowCache
\r
198 cache.normalized.push(cols);
\r
202 if(table.config.debug) { benchmark("Building cache for " + totalRows + " rows:", cacheTime); }
\r
207 function getElementText(config,node) {
\r
209 if(!node) return "";
\r
214 if(typeof(config.textExtraction) == "function") {
\r
215 t = config.textExtraction(node);
\r
216 } else if(config.textExtraction == "complex") {
\r
217 t = $(node).text();
\r
219 if(node.childNodes[0] && node.childNodes[0].hasChildNodes()) {
\r
220 t = node.childNodes[0].innerHTML;
\r
222 t = node.innerHTML;
\r
228 function appendToTable(table,cache) {
\r
230 if(table.config.debug) {var appendTime = new Date()}
\r
235 totalRows = n.length,
\r
236 checkCell = (n[0].length-1),
\r
237 tableBody = $("tbody:first",table).empty();
\r
240 for (var i=0;i < totalRows; i++) {
\r
241 rows.push(r[n[i][checkCell]]);
\r
242 if(table.config.appender == null) {
\r
243 tableBody.append(r[n[i][checkCell]]);
\r
247 if(table.config.appender != null) {
\r
248 table.config.appender(table,rows);
\r
253 //apply table widgets
\r
254 applyWidget(table);
\r
256 if(table.config.debug) { benchmark("Rebuilt table:", appendTime); }
\r
260 function buildHeaders(table) {
\r
262 if(table.config.debug) { var time = new Date(); }
\r
264 var meta = ($.meta) ? true : false, tableHeadersRows = [];
\r
266 for(var i = 0; i < table.tHead.rows.length; i++) { tableHeadersRows[i]=0; };
\r
268 $tableHeaders = $(checkCellColSpan(table, tableHeadersRows, 0,table.tHead.rows[0].cells.length));
\r
270 $tableHeaders.each(function(index) {
\r
273 this.column = index;
\r
274 this.order = formatSortingOrder(table.config.sortInitialOrder);
\r
276 if(checkHeaderMetadata(this) || checkHeaderOptions(table,index)) this.sortDisabled = true;
\r
278 if(!this.sortDisabled) {
\r
279 $(this).addClass(table.config.cssHeader);
\r
282 // add cell to headerList
\r
283 table.config.headerList[index]= this;
\r
286 if(table.config.debug) { benchmark("Built headers:", time); log($tableHeaders); }
\r
288 return $tableHeaders;
\r
292 function checkCellColSpan(table, headerArr, row) {
\r
293 var arr = [], r = table.tHead.rows, c = r[row].cells;
\r
295 for(var i=headerArr[row]; i < c.length; i++) {
\r
298 if ( cell.colSpan > 1) {
\r
299 arr = arr.concat(checkCellColSpan(table, headerArr,row+cell.rowSpan));
\r
301 if(table.tHead.length == 1 || (cell.rowSpan > 1 || !r[row+1])) {
\r
304 headerArr[row] = (i+row);
\r
310 function checkHeaderMetadata(cell) {
\r
311 if(($.meta) && ($(cell).data().sorter === false)) { return true; };
\r
315 function checkHeaderOptions(table,i) {
\r
316 if((table.config.headers[i]) && (table.config.headers[i].sorter === false)) { return true; };
\r
320 function applyWidget(table) {
\r
321 var c = table.config.widgets;
\r
323 for(var i=0; i < l; i++) {
\r
325 getWidgetById(c[i]).format(table);
\r
330 function getWidgetById(name) {
\r
331 var l = widgets.length;
\r
332 for(var i=0; i < l; i++) {
\r
333 if(widgets[i].id.toLowerCase() == name.toLowerCase() ) {
\r
334 return widgets[i];
\r
339 function formatSortingOrder(v) {
\r
341 if(typeof(v) != "Number") {
\r
342 i = (v.toLowerCase() == "desc") ? 1 : 0;
344 i = (v == (0 || 1)) ? v : 0;
349 function isValueInArray(v, a) {
\r
351 for(var i=0; i < l; i++) {
\r
359 function setHeadersCss(table,$headers, list, css) {
\r
360 // remove all header information
\r
361 $headers.removeClass(css[0]).removeClass(css[1]);
\r
364 $headers.each(function(offset) {
\r
365 if(!this.sortDisabled) {
\r
366 h[this.column] = $(this);
\r
370 var l = list.length;
\r
371 for(var i=0; i < l; i++) {
\r
372 h[list[i][0]].addClass(css[list[i][1]]);
\r
376 function fixColumnWidth(table,$headers) {
\r
377 var c = table.config;
\r
379 var colgroup = $('<colgroup>');
\r
380 $("tbody:first tr:first td",table).each(function() {
\r
382 colgroup.append($('<col>').css('width',$(this).width()));
\r
385 $(table).prepend(colgroup);
\r
389 function updateHeaderSortCount(table,sortList) {
\r
390 var c = table.config, l = sortList.length;
\r
391 for(var i=0; i < l; i++) {
\r
392 var s = sortList[i], o = c.headerList[s[0]];
\r
398 /* sorting methods */
\r
399 function multisort(table,sortList,cache) {
\r
401 if(table.config.debug) { var sortTime = new Date(); }
\r
403 var dynamicExp = "var sortWrapper = function(a,b) {", l = sortList.length;
\r
405 for(var i=0; i < l; i++) {
\r
407 var c = sortList[i][0];
\r
408 var order = sortList[i][1];
\r
409 var s = (getCachedSortType(table.config.parsers,c) == "text") ? ((order == 0) ? "sortText" : "sortTextDesc") : ((order == 0) ? "sortNumeric" : "sortNumericDesc");
\r
413 dynamicExp += "var " + e + " = " + s + "(a[" + c + "],b[" + c + "]); ";
\r
414 dynamicExp += "if(" + e + ") { return " + e + "; } ";
\r
415 dynamicExp += "else { ";
\r
418 for(var i=0; i < l; i++) {
\r
419 dynamicExp += "}; ";
\r
422 dynamicExp += "return 0; ";
\r
423 dynamicExp += "}; ";
\r
427 cache.normalized.sort(sortWrapper);
\r
429 if(table.config.debug) { benchmark("Sorting on " + sortList.toString() + " and dir " + order+ " time:", sortTime); }
\r
434 function sortText(a,b) {
\r
435 return ((a < b) ? -1 : ((a > b) ? 1 : 0));
\r
438 function sortTextDesc(a,b) {
\r
439 return ((b < a) ? -1 : ((b > a) ? 1 : 0));
\r
442 function sortNumeric(a,b) {
\r
446 function sortNumericDesc(a,b) {
\r
450 function getCachedSortType(parsers,i) {
\r
451 return parsers[i].type;
\r
454 /* public methods */
\r
455 this.construct = function(settings) {
\r
457 return this.each(function() {
\r
462 var $this, $document,$headers, cache, config, shiftDown = 0, sortOrder;
\r
466 config = $.extend(this.config, $.tablesorter.defaults, settings);
\r
468 if(!this.tHead || !this.tBodies) return true;
\r
470 // store common expression for speed
\r
474 $headers = buildHeaders(this);
\r
476 // try to auto detect column type, and store in tables config
\r
477 this.config.parsers = buildParserCache(this,$headers);
\r
480 // build the cache for the tbody cells
\r
481 cache = buildCache(this);
\r
483 // get the css class names, could be done else where.
\r
484 var sortCSS = [config.cssDesc,config.cssAsc];
\r
486 // fixate columns if the users supplies the fixedWidth option
\r
487 fixColumnWidth(this);
\r
489 // apply event handling to headers
\r
490 // this is to big, perhaps break it out?
\r
491 $headers.click(function(e) {
\r
492 if(!this.sortDisabled) {
\r
493 // store exp, for speed
\r
494 var $cell = $(this);
\r
496 // get current column index
\r
497 var i = this.column;
\r
499 // get current column sort order
\r
500 this.order = this.count++ % 2;
\r
504 // user only whants to sort on one column
\r
505 if(!e[config.sortMultiSortKey]) {
\r
507 // flush the sort list
\r
508 config.sortList = [];
\r
510 if(config.sortForce != null) {
\r
511 var a = config.sortForce;
\r
512 for(var j=0; j < a.length; j++) {
\r
513 config.sortList.push(a[j]);
\r
517 // add column to sort list
\r
518 config.sortList.push([i,this.order]);
\r
520 // multi column sorting
\r
522 // the user has clicked on an all ready sortet column.
\r
523 if(isValueInArray(i,config.sortList)) {
\r
525 // revers the sorting direction for all tables.
\r
526 for(var j=0; j < config.sortList.length; j++) {
\r
527 var s = config.sortList[j], o = config.headerList[s[0]];
\r
531 s[1] = o.count % 2;
\r
535 // add column to sort list array
\r
536 config.sortList.push([i,this.order]);
\r
540 //set css for headers
\r
541 setHeadersCss($this[0],$headers,config.sortList,sortCSS);
\r
543 // sort the table and append it to the dom
\r
544 appendToTable($this[0],multisort($this[0],config.sortList,cache));
\r
546 // stop normal event by returning false
\r
550 }).mousedown(function() {
\r
551 if(config.cancelSelection) {
\r
552 this.onselectstart = function() {return false};
\r
553 //alert(this.onselectstart);
\r
558 // apply easy methods that trigger binded events
\r
559 $this.bind("update",function() {
\r
561 // rebuild the cache map
\r
562 cache = buildCache(this);
\r
564 }).bind("sorton",function(e,list) {
\r
566 // update and store the sortlist
\r
567 var sortList = config.sortList = list;
\r
569 // update header count index
\r
570 updateHeaderSortCount(this,sortList);
\r
572 //set css for headers
\r
573 setHeadersCss(this,$headers,sortList,sortCSS);
\r
575 // sort the table and append it to the dom
\r
576 appendToTable(this,multisort(this,sortList,cache));
\r
578 }).bind("appendCache",function() {
\r
580 appendToTable(this,cache);
\r
582 }).bind("applyWidgetId",function(e,id) {
\r
584 getWidgetById(id).format(this);
\r
588 if($.meta && ($(this).data() && $(this).data().sortlist)) {
\r
589 config.sortList = $(this).data().sortlist;
\r
591 // if user has supplied a sort list to constructor.
\r
592 if(config.sortList.length > 0) {
\r
593 $this.trigger("sorton",[config.sortList]);
\r
601 this.addParser = function(parser) {
\r
602 var l = parsers.length, a = true;
\r
603 for(var i=0; i < l; i++) {
\r
604 if(parsers[i].id.toLowerCase() == parser.id.toLowerCase()) {
\r
608 if(a) { parsers.push(parser); };
\r
611 this.addWidget = function(widget) {
\r
612 widgets.push(widget);
\r
615 this.formatFloat = function(s) {
\r
617 var i = parseFloat(s);
\r
618 return (isNaN(i)) ? 0 : i;
\r
620 this.formatInt = function(s) {
\r
621 var i = parseInt(s);
\r
622 return (isNaN(i)) ? 0 : i;
\r
628 // extend plugin scope
\r
630 tablesorter: $.tablesorter.construct
\r
633 // add default parsers
\r
634 $.tablesorter.addParser({
\r
639 format: function(s) {
\r
640 return $.trim(s.toLowerCase());
\r
645 $.tablesorter.addParser({
\r
648 return s.match(new RegExp(/^\d+$/));
\r
650 format: function(s) {
\r
651 return $.tablesorter.formatInt(s);
\r
656 $.tablesorter.addParser({
\r
659 return /^[£$€?.]/.test(s);
\r
661 format: function(s) {
\r
662 return $.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9.]/g),""));
\r
667 $.tablesorter.addParser({
\r
670 return /^\d+$/.test(s);
\r
672 format: function(s) {
\r
673 return $.tablesorter.formatFloat(s);
\r
678 $.tablesorter.addParser({
\r
681 return s.match(new RegExp(/^(\+|-)?[0-9]+\.[0-9]+((E|e)(\+|-)?[0-9]+)?$/));
\r
683 format: function(s) {
\r
684 return $.tablesorter.formatFloat(s.replace(new RegExp(/,/),""));
\r
689 $.tablesorter.addParser({
\r
692 return /^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);
\r
694 format: function(s) {
\r
695 var a = s.split(".");
\r
697 for (var i = 0, item; item = a[i]; i++) {
\r
698 if(item.length == 2) {
\r
704 return $.tablesorter.formatFloat(s);
\r
709 $.tablesorter.addParser({
\r
712 return /^(https?|ftp|file):\/\/$/.test(s);
\r
714 format: function(s) {
\r
715 return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));
\r
720 $.tablesorter.addParser({
\r
723 return /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);
\r
725 format: function(s) {
\r
726 return $.tablesorter.formatFloat((s != "") ? new Date(s.replace(new RegExp(/-/g),"/")).getTime() : "0");
\r
731 $.tablesorter.addParser({
\r
734 return /^\d{1,3}%$/.test(s);
\r
736 format: function(s) {
\r
737 return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));
\r
742 $.tablesorter.addParser({
\r
745 return /^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|\'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/.test(s);
\r
747 format: function(s) {
\r
748 return $.tablesorter.formatFloat(new Date(s).getTime());
\r
753 $.tablesorter.addParser({
\r
756 return /\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}/.test(s);
\r
758 format: function(s,table) {
\r
759 var c = table.config;
\r
760 s = s.replace(new RegExp(/-/g),"/");
\r
761 if(c.dateFormat == "us") {
\r
762 /** reformat the string in ISO format */
\r
763 s = s.replace(new RegExp(/(\d{1,2})[\/-](\d{1,2})[\/-](\d{4})/), "$3/$1/$2");
\r
764 } else if(c.dateFormat == "uk") {
\r
765 /** reformat the string in ISO format */
\r
766 s = s.replace(new RegExp(/(\d{1,2})[\/-](\d{1,2})[\/-](\d{4})/), "$3/$2/$1");
\r
767 } else if(c.dateFormat == "dd/mm/yy" || c.dateFormat == "dd-mm-yy") {
\r
768 s = s.replace(new RegExp(/(\d{1,2})[\/-](\d{1,2})[\/-](\d{2})/), "$1/$2/$3");
\r
770 return $.tablesorter.formatFloat(new Date(s).getTime());
\r
775 $.tablesorter.addParser({
\r
778 return /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);
\r
780 format: function(s) {
\r
781 return $.tablesorter.formatFloat(new Date("2000/01/01 " + s).getTime());
\r
787 $.tablesorter.addParser({
\r
792 format: function(s,table,cell) {
\r
793 var c = table.config, p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName;
\r
794 return $(cell).data()[p];
\r
799 // add default widgets
\r
800 $.tablesorter.addWidget({
\r
802 format: function(table) {
\r
803 $("> tbody:first/tr:visible:even",table).removeClass(table.config.widgetZebra.css[1]).addClass(table.config.widgetZebra.css[0]);
\r
804 $("> tbody:first/tr:visible:odd",table).removeClass(table.config.widgetZebra.css[0]).addClass(table.config.widgetZebra.css[1]);
\r