title: Javascript sort table column on click
body: <p>My intention is to sort a table column (only the clicked th's column) in ascending order when <code>th</code> is being clicked. On further click the exact table column shall be ordered in a descending order. </p>
  
  <p><strong>What I got so far: <br>
  The table is being sorted, but on click all three columns are being sorted - I only want one column to be sorted.</strong> </p>
  
  <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>function sortTable(n) {
      var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
      table = document.getElementById("table");
      switching = true;
      dir = "asc";
  
      while (switching) {
          switching = false;
          rows = table.rows;
  
          for (i = 1; i &lt; (rows.length - 1); i++) {
              shouldSwitch = false;
              x = rows[i].getElementsByTagName("TD")[n];
              y = rows[i + 1].getElementsByTagName("TD")[n];
  
              if (dir == "asc") {
                  if (x.innerHTML.toLowerCase() &gt; y.innerHTML.toLowerCase()) {
                      shouldSwitch = true;
                      break;
                  }
              } else if (dir == "desc") {
                  if (x.innerHTML.toLowerCase() &lt; y.innerHTML.toLowerCase()) {
                      shouldSwitch = true;
                      break;
                  }
              }
          }
          if (shouldSwitch) {
              rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
              switching = true;
              switchcount ++;
          } else {
              if (switchcount == 0 &amp;&amp; dir == "asc") {
                  dir = "desc";
                  switching = true;
              }
          }
      }
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table id="table"&gt;
        &lt;tr&gt;
          &lt;th onclick="sortTable(0)"&gt;Nummer&lt;/th&gt;
          &lt;th onclick="sortTable(1)"&gt;Land&lt;/th&gt;
          &lt;th onclick="sortTable(2)"&gt;Name&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;2&lt;/td&gt;
          &lt;td&gt;Rumänien&lt;/td&gt;
          &lt;td&gt;Dan&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;1&lt;/td&gt;
          &lt;td&gt;Deutschland&lt;/td&gt;
          &lt;td&gt;Aaron&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;3&lt;/td&gt;
          &lt;td&gt;USA&lt;/td&gt;
          &lt;td&gt;Peter&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;</code></pre>
  </div>
  </div>
  </p>