Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 380
Chris Conway Avatar asked May 19 '09 13:05

Chris Conway


People also ask

How can add Li in UL dynamically using jQuery?

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.

How do you add an item to a list in HTML?

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.

What is ADD method in jQuery?

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.

Which method would you use to add one new item Li item in the beginning of ordered list?

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.


2 Answers

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

like image 73
Plutor Avatar answered Sep 19 '22 17:09

Plutor


<script type="text/javascript">
     $(document).ready(function(){
     $("#doctype li:first").before("<li><a href='intranet/library'>All documents</a></li>");
     });
</script>
like image 26
irshad Avatar answered Sep 18 '22 17:09

irshad