Dustkicker
unread,Mar 6, 2009, 1:56:01 AM3/6/09Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Sign in to report message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Flexigrid for jQuery
I wrote a function to perform sorting of the table locally instead of
making a trip to the server each time. It uses the ".sorted" class to
determine which column needs sorting, thus only the table selector is
passed along with the sort order. At this stage it supports alphabetic
and (slightly crude) numeric sorting. I hope this helps someone.
Suggestions welcome.
Here is the function:
========================================
function sortGrid(table, order) {
// Remove all characters in c from s.
var stripChar = function(s, c) {
var r = "";
for(var i = 0; i < s.length; i++) {
r += c.indexOf(s.charAt(i))>=0 ? "" : s.charAt(i);
}
return r;
}
// Test for characters accepted in numeric values.
var isNumeric = function(s) {
var valid = "0123456789.,- ";
var result = true;
var c;
for(var i = 0; i < s.length && result; i++) {
c= s.charAt(i);
if(valid.indexOf(c) <= -1) {
result = false;
}
}
return result;
}
// Sort table rows.
var asc = order == "asc";
var rows = $(table).find("tbody > tr").get();
var column = $(table).parent(".bDiv").siblings(".hDiv").find
("table tr th").index($("th.sorted", ".flexigrid:has(" + table +
")"));
rows.sort(function(a, b) {
var keyA = $(asc? a : b).children("td").eq(column).text
().toUpperCase();
var keyB = $(asc? b : a).children("td").eq(column).text
().toUpperCase();
if((isNumeric(keyA)||keyA.length<1) && (isNumeric(keyB)||
keyB.length<1)) {
keyA = stripChar(keyA,", ");
keyB = stripChar(keyB,", ");
if(keyA.length < 1) keyA = 0;
if(keyB.length < 1) keyB = 0;
keyA = new Number(parseFloat(keyA));
keyB = new Number(parseFloat(keyB));
}
return keyA>keyB ? 1 : keyA<keyB ? -1 : 0;
});
// Rebuild the table body.
$.each(rows, function(index, row) {
$(table).children("tbody").append(row);
});
// Fix styles
$(table).find("tr").removeClass("erow"); // Clear the striping.
$(table).find("tr:odd").addClass("erow"); // Add striping to odd
numbered rows.
$(table).find("td.sorted").removeClass("sorted"); // Clear sorted
class from table cells.
$(table).find("tr").each( function(){
$(this).find("td:nth(" + column + ")").addClass("sorted"); //
Add sorted class to sorted column cells.
});
}
========================================
To use it, setup flexigrid and override the onChangeSort function e.g.
$("#table").flexigrid({
...
onChangeSort: function(name, order) {
sortGrid("#table", order);
}
...
});
Regards,
Kobus