I'm working through a jQuery book and am currently on the chapter of table sorting. Using the example code in the book I've set up the following test scenario, when I click on a column heading it correctly sorts the data one way (ascending), but when I click on the same column heading again nothing happens (I'm expecting the data to be sorted descending on the 2nd click).
Can anybody take a look at the sample code below and tell me why this is?
HTML:
<table class="sortable">
<thead>
<tr>
<th class="sort-alpha"><strong>Flat number</strong></th>
<th class="sort-alpha"><strong>Tenant name</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>83</td>
<td>Rachel Prouse</td>
</tr>
<tr>
<td>79</td>
<td>Natalie Charles</td>
</tr>
</tbody>
</table>
jQuery:
$(document).ready(function () {
$('table.sortable').each(function() {
var $table = $(this);
$('th', $table).each(function(column) {
var $header = $(this);
if ($header.is('.sort-alpha')) {
$header
.addClass('clickable')
.hover(
function() { $header.addClass('hover') },
function() { $header.removeClass('hover');
})
.click(function() {
var rows = $table.find('tbody > tr').get();
rows.sort(function(a, b) {
var keyA = $(a).children('td').eq(column).text().toUpperCase();
var keyB = $(b).children('td').eq(column).text().toUpperCase();
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
});
$.each(rows, function(index, row) {
$table.children('tbody').append(row);
});
});
}
});
});
});