javascript - Sorting an HTML list ascending and descending, with jQuery -


i have "numbered" list of names. want sort alphabetically @ click of button, after choosing sort criteria drop-down list (select).

the problem that, if sort items ascending , descending, descending sorted items placed after ascending sorted ones. list gets bigger.

$(document).ready(function(){    var sortitems = function() {      var sortednames = [];      var sorteditms = [];      var rawnames  = $('.list').find('li');      (var = 0; < 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 = [];        (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 doing wrong?

thank you!

you have clear sorteditms.

var setitems = function () {      sorteditms = [];       (var j = 0; j < sortednames.length; j++) {         var sorteditm = '<li>' + sortednames[j] + '</li>';         sorteditms.push(sorteditm);       }       sorteditms.join('');       $('.list').html(sorteditms);     } 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -