Created
June 27, 2010 13:44
-
-
Save kidsil/454917 to your computer and use it in GitHub Desktop.
Sorting Table by column
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//written by seth from StackOverFlow | |
//Thanks. | |
// sorting function for the headers | |
function th_sorter(a, b) { | |
// just compare the text | |
var cmp = $(a).text() > $(b).text(); | |
if (cmp) { | |
return 1; | |
} | |
else { | |
return $(a).text() === $(b).text() ? -1 : 0; | |
} | |
} | |
var sorted = [], temp=[]; | |
// first sort the 1st row so we can figure out what goes where | |
$('table tr:first').each( | |
function(i, tr) { | |
$(tr).children('td').each( function(idx,node) { | |
$(node).data('orig', idx); | |
}).sort( th_sorter ).each( function(idx, node) { | |
sorted.push( { | |
html: $(node).html(), | |
idx: $(node).data('orig') | |
} ); | |
}); | |
}); | |
// now re-arrange the deck chairs | |
$('table tr').each( function(i, tr) { | |
// double each, once to capture and once to move | |
$(tr).children('td').each( function( idx, node) { | |
temp[idx] = $(node).html(); | |
}).each( function(idx,node) { | |
$(node).html( temp[ sorted[idx].idx ] ); | |
}); | |
temp = []; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment