Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery table sort function only sorting one-way
    primarykey
    data
    text
    <p>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). </p> <p>Can anybody take a look at the sample code below and tell me why this is?</p> <p><strong>HTML:</strong></p> <pre><code>&lt;table class="sortable"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="sort-alpha"&gt;&lt;strong&gt;Flat number&lt;/strong&gt;&lt;/th&gt; &lt;th class="sort-alpha"&gt;&lt;strong&gt;Tenant name&lt;/strong&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;83&lt;/td&gt; &lt;td&gt;Rachel Prouse&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;79&lt;/td&gt; &lt;td&gt;Natalie Charles&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p><strong>jQuery:</strong></p> <pre><code>$(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 &gt; 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 &lt; keyB) return -1; if (keyA &gt; keyB) return 1; return 0; }); $.each(rows, function(index, row) { $table.children('tbody').append(row); }); }); } }); }); }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload