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; var $table = $('#mytable'); var $rows = $('tbody > tr',$table); $rows.sort(function(a, b) { var keyA = $('td:eq(0)',a).text(); var keyB = $('td:eq(0)',b).text(); if($($sort).hasClass('asc')) { return (keyA > keyB) ? 1 : 0; } else { return (keyA < keyB) ? 1 : 0; } });
Sort Table by Clicking the Headers. Click the headers to sort the table. Click "Name" to sort by names, and "Country" to sort by country. The first time you click, the sorting direction is ascending (A to Z).
How to Make Sortable Tables. Adding the "sortable" class to a <table> element provides support for sorting by column value. Clicking the column headers will sort the table rows by that column's value. Tables must use <thead> and <th> tags for sortable functionality to work.
Something like this
function sortTable(table, order) { var asc = order === 'asc', tbody = table.find('tbody'); tbody.find('tr').sort(function(a, b) { if (asc) { return $('td:first', a).text().localeCompare($('td:first', b).text()); } else { return $('td:first', b).text().localeCompare($('td:first', a).text()); } }).appendTo(tbody); }
could be called on any table like this
sortTable($('#mytable'),'asc');
FIDDLE
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With