Avatar of skij
skij
Flag 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

jQuery

Avatar of undefined
Last Comment
Robert Schutt

8/22/2022 - Mon
Robert Schutt

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
Robert Schutt

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23