title: Sorting an HTML list ascending and descending, with jQuery
body: <p>I have a "numbered" list of names. I want to sort it alphabetically at the click of a button, but only <em>after choosing a sort criteria</em> from a drop-down list (select).</p>
  
  <p>The problem is that, if i sort the items ascending and then descending, the descending sorted items are placed <em>after</em> the ascending sorted ones. The list gets bigger.</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>$(document).ready(function(){
    var sortItems = function() {
      var sortedNames = [];
      var sortedItms = [];
      var rawNames  = $('.list').find('li');
      for (var i = 0; i &lt; rawNames.length; i++) {
        var names = $(rawNames[i]).text();
        sortedNames.push(names);
      }
  
      $('#choose_order').on('change', function(){
        var currVal = $(this).find("option:selected").val();
        console.log(currVal);
        if (currVal != 'default') {
          $('#sortbtn').removeClass("disabled");
          if (currVal == 'asc') {
            sortedNames.sort();
          } else {
            sortedNames.sort();
            sortedNames.reverse();
          }
        } else {
          $('#sortbtn').addClass("disabled");
        }
      });
  
      var setItems = function () {
       sortedItms = [];
        for (var j = 0; j &lt; sortedNames.length; j++) {
          var sortedItm = '&lt;li&gt;' + sortedNames[j] + '&lt;/li&gt;';
          sortedItms.push(sortedItm);
        }
        sortedItms.join('');
        $('.list').html(sortedItms);
      }
  
      $('#sortbtn').on('click', setItems);
    }
    $(window).on('load', sortItems);
  
  });</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/&gt;
  &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"&gt;&lt;/script&gt;
  &lt;div class="pannel"&gt;
    &lt;select name="choose_order" id="choose_order"&gt;
      &lt;option value="default" selected="selected"&gt;Choose sorting order&lt;/option&gt;
      &lt;option value="asc"&gt;Ascending&lt;/option&gt;
      &lt;option value="desc"&gt;Descending&lt;/option&gt;
    &lt;/select&gt;
    &lt;div class="buttons_container"&gt;
      &lt;a class="btn btn-success disabled" id="sortbtn"&gt;Sort&lt;/a&gt;
    &lt;/div&gt;
    &lt;ol class="list"&gt;
      &lt;li&gt;Cosmin&lt;/li&gt;
      &lt;li&gt;Alina&lt;/li&gt;
      &lt;li&gt;Diana&lt;/li&gt;
      &lt;li&gt;Elena&lt;/li&gt;
      &lt;li&gt;Bogdan&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>What am i doing wrong? </p>
  
  <p>Thank you!</p>