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!
I think this would work:
The value of
firstafteritemwill 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.)