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!
Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element. The following example will add a <li> element at the end of an <ul> on click of the button.
In HTML, we can create an ordered list using the <ol> tag. The ol in the tag stands for an ordered list. Inside each of the ordered list elements <ol> and <ol /> , we have to define the list items. We can define the list items using the <li> tag.
jQuery add() Method The add() method adds elements to an existing group of elements. This method adds elements on the whole document, or just inside context elements if the context parameter is specified.
With jQuery, you can create a new <li> element and add it to an existing <ol> or <ul> element using the . append() or the . prepend() method.
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.)
<script type="text/javascript">
$(document).ready(function(){
$("#doctype li:first").before("<li><a href='intranet/library'>All documents</a></li>");
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With