user1647234 user1647234 - 2 months ago 7
jQuery Question

Sorting an HTML list ascending and descending, with jQuery

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!

Answer

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);
    }