views:

3229

answers:

5

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!

+4  A: 

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.)

Plutor
This worked perfectly! Thank you!
Chris Conway
A: 

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); }
larson4
A: 

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.

Blindy
A: 

Can anyone tell me how can i delete a comment from this forum?

sushyl
A: 
<script type="text/javascript">
     $(document).ready(function(){
     $("#doctype li:first").before("<li><a href='intranet/library'>All documents</a></li>");
     });
</script>
irshad
Welcome to StackOverflow, @irshad. Take the time to have a look at how to format your answers: http://stackoverflow.com/editing-help =)
David Thomas