Chris Conway
Chris Conway

Reputation: 16519

How can I add a list item in order using jQuery?

Does anyone know how to add an item to a list but do it so it's ordered alphabetically using jQuery? I've got the following code that just adds an item from a dropdown to the end of the list:

$("#projectList").append(
    "<li>"
    + $("#Projects :selected").text()
    + " <span class='removeProject' projectId='" + $("#Projects").val() + "'>Remove</span>"
    + "</li>"
);

but I'd like to be able to insert it in its appropriate place instead of just appending to the end of the existing list.

Any help is greatly appreciated! Thanks!

Upvotes: 9

Views: 13869

Answers (4)

irshad
irshad

Reputation: 11

<script type="text/javascript">
     $(document).ready(function(){
     $("#doctype li:first").before("<li><a href='intranet/library'>All documents</a></li>");
     });
</script>

Upvotes: 1

Blindy
Blindy

Reputation: 67380

You can parse the list to see where your item should be added and then use the after() jquery function to add your item in place.

Upvotes: 0

jwl
jwl

Reputation: 10514

I don't think there is an easy way with core jQuery at least.

Off the top of my head, untested, something simple like this might work if your list is short (since its O(N) )

var liArr=$("#projectList li").get();
var newText=$("#Projects :selected").text();
var newEle=$("<li>"
    + newText
    + " <span class='removeProject' projectId='" + $("#Projects").val() + "'>Remove</span>"
    + "</li>");
for(var li=0; li<liArr.length; li++) {
  if(newText<liArr[li].innerHTML) {
     $("#projectList").get(0).insertBefore(newEle,liArr[li]);
     newEle=null;
     break;
     } 
  }
if(newEle) { $("#projectList").append(newEle); }

Upvotes: 0

Plutor
Plutor

Reputation: 2897

I think this would work:

var new = $(
    "<li>"
    + $("#Projects :selected").text()
    + " <span class='removeProject' projectId='" + $("#Projects").val() + "'>Remove</span>"
    + "</li>"
);

var firstafteritem = $("#projectList").children().filter( function () {
    return ($(this).text() > $("#Projects :selected").text())
} ).eq(0);

if (firstafteritem.length > 0) firstafteritem.before(new);
else                           $("#projectList").append(new);

The value of firstafteritem will be the first list item that has a text value after the one you're adding. (Or none if it would be last.) Then the if/else would either insert it before that item or at the end of the list.

(This, of course, assumes that the values of your list are already in order.)

Upvotes: 8

Related Questions