0

I have a "numbered" list of names. I want to sort it alphabetically at the click of a button, but only after choosing a sort criteria from a drop-down list (select).

The problem is that, if i sort the items ascending and then descending, the descending sorted items are placed after the ascending sorted ones. The list gets bigger.

$(document).ready(function(){
  var sortItems = function() {
    var sortedNames = [];
    var sortedItms = [];
    var rawNames  = $('.list').find('li');
    for (var i = 0; i < 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 < sortedNames.length; j++) {
        var sortedItm = '<li>' + sortedNames[j] + '</li>';
        sortedItms.push(sortedItm);
      }
      sortedItms.join('');
      $('.list').html(sortedItms);
    }

    $('#sortbtn').on('click', setItems);
  }
  $(window).on('load', sortItems);

});
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="pannel">
  <select name="choose_order" id="choose_order">
    <option value="default" selected="selected">Choose sorting order</option>
    <option value="asc">Ascending</option>
    <option value="desc">Descending</option>
  </select>
  <div class="buttons_container">
    <a class="btn btn-success disabled" id="sortbtn">Sort</a>
  </div>
  <ol class="list">
    <li>Cosmin</li>
    <li>Alina</li>
    <li>Diana</li>
    <li>Elena</li>
    <li>Bogdan</li>
  </ol>
</div>

What am i doing wrong?

Thank you!

  • Possible duplicate of http://stackoverflow.com/questions/8837191/sort-an-html-list-with-javascript – Redu Sep 22 '16 at 14:47
  • 1
    You're doing `.push` to add the items to your `sortedItms` array, but I don't see you clearing the array anywhere. You should be replacing the items in this array with each sort, rather than adding to it. – Tyler Roper Sep 22 '16 at 14:48

1 Answers1

0

You have to clear your sortedItms.

var setItems = function () {
     sortedItms = [];
      for (var j = 0; j < sortedNames.length; j++) {
        var sortedItm = '<li>' + sortedNames[j] + '</li>';
        sortedItms.push(sortedItm);
      }
      sortedItms.join('');
      $('.list').html(sortedItms);
    }
Anton Chukanov
  • 645
  • 5
  • 20