Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I came across this, and thought I'd throw in my 2 cents. Click on the column headers to sort ascending, and again to sort descending.</p> <ul> <li>Works in Chrome, Firefox, Opera AND IE(8)</li> <li>Only uses JQuery</li> <li>Does alpha and numeric sorting - ascending and descending</li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('th').click(function(){ var table = $(this).parents('table').eq(0) var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index())) this.asc = !this.asc if (!this.asc){rows = rows.reverse()} for (var i = 0; i &lt; rows.length; i++){table.append(rows[i])} }) function comparer(index) { return function(a, b) { var valA = getCellValue(a, index), valB = getCellValue(b, index) return $.isNumeric(valA) &amp;&amp; $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB) } } function getCellValue(row, index){ return $(row).children('td').eq(index).text() }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>table, th, td { border: 1px solid black; } th { cursor: pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;table&gt; &lt;tr&gt;&lt;th&gt;Country&lt;/th&gt;&lt;th&gt;Date&lt;/th&gt;&lt;th&gt;Size&lt;/th&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;France&lt;/td&gt;&lt;td&gt;2001-01-01&lt;/td&gt;&lt;td&gt;25&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;a href=#&gt;spain&lt;/a&gt;&lt;/td&gt;&lt;td&gt;2005-05-05&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Lebanon&lt;/td&gt;&lt;td&gt;2002-02-02&lt;/td&gt;&lt;td&gt;-17&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Argentina&lt;/td&gt;&lt;td&gt;2005-04-04&lt;/td&gt;&lt;td&gt;100&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;USA&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;-6&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <h2>** Update: 2018</h2> <ul> <li>For those that are interested, I've provided an <a href="https://stackoverflow.com/a/49041392/782034">ES6 Plain Javascript solution here</a>.</li> </ul>
 

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