I got struck in sorting tds in table using jquery.
My Demo fiddle
How can I call it for any table with id in my project?
var $sort = this;
v
I think you are missing the final "reset" function to sort the table. The desc code will not work because the order must be switched.
Code:
$('.sort').click(function (e) {
var $sort = this;
var $table = $('#mytable');
var $rows = $('tbody > tr', $table);
$rows.sort(function (a, b) {
var keyA = $('td', a).text();
var keyB = $('td', b).text();
if ($($sort).hasClass('asc')) {
return (keyA > keyB) ? 1 : 0;
} else {
return (keyA > keyB) ? 0 : 1;
}
});
$.each($rows, function (index, row) {
$table.append(row);
});
e.preventDefault();
});
Demo: http://jsfiddle.net/7wwvL/
More in general your function can be:
function sortTable($table,order){
var $rows = $('tbody > tr', $table);
$rows.sort(function (a, b) {
var keyA = $('td', a).text();
var keyB = $('td', b).text();
if (order=='asc') {
return (keyA > keyB) ? 1 : 0;
} else {
return (keyA > keyB) ? 0 : 1;
}
});
$.each($rows, function (index, row) {
$table.append(row);
});
}
sortTable($('#mytable'),'asc')
Demo: http://jsfiddle.net/d7Kbx/