Link to home
Start Free TrialLog in
Avatar of skij
skijFlag for Canada

asked on

jQuery: Mainting Sort Order When Inserting Item

This adds the mangoes to the end of the list.  I want them to be added so that the list remains in alphabetical order.

<!DOCTYPE html>
<html lang="en">
<title>Demo</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">

$( document ).ready(function() {

 $('ul').append('<li>Mangos</li>');
  
});

</script>
<body>

 <ul>
  <li>Apples</li>
  <li>Bananas</li>
  <li>Grapes</li>
  <li>Peaches</li>
  <li>Pears</li>
  <li>Watermellon</li>
 </ul>

</body>
</html>

Open in new window

Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Here's a function you can use:
<script type="text/javascript">

$.fn.sortChildren = function() {
  return $(this).each(function(i,ul){
    $(ul).children().sort(function(a,b){
      return $(a).text() > $(b).text();
    }).each(function(idx,obj){
      // move each element to the end in order
      $(ul).append($(obj));
    });
  });
};

$( document ).ready(function() {

 $('ul').append('<li>Mangos</li>');
 $('ul').sortChildren();

});

</script>

Open in new window

I also made a jsFiddle to show some more options: https://jsfiddle.net/robert_schutt/jjf63utu/
ASKER CERTIFIED SOLUTION
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial