JQuery - create a new sibling element between two existing elements based on the value of identifiers

I am creating a list of calendars of a dynamic event, and I am trying to figure out a way to add a new element between two elements based on their identifiers. Existing elements have an identifier that is formatted to be used as the date of the event.

ID generated by yymmdd date

Example

<li id="120523">
    This would be an event for May 23rd, 2012
</li>

<li id="120525">
    This would be for May 25th, 2012
</li>

What I'm trying to do is dynamically create a new event and place it in the right place. For example: if the user creates another event for May 24, 2012, he should be placed between two characters.

dymanic, , , , , ID, , , ID , .

:

- :

<li id="120504">May 4, 2012<li>

id :

<ul>
<li id="120123">Jan 23, 2012</li>
<li id="120415">April 15, 2012</li>
<li id="120502">May 2, 2012</li>
// new element should go here
<li id="120520">May 20, 2012</li>
<li id="120816">Aug 16, 2012</li>
</ul>

jQuery

+5
2

: http://jsfiddle.net/UJdaW/

$(function(){
    $(".date").datepicker();
    $("#add").click(function(){
        var id = parseInt( $.datepicker.formatDate('ymmdd', new Date($(".date").val())));
        var el = $("<li>This would be for " + $(".date").val() + "</li>").attr("id",id)
        var lastLi = null;
        $("li").each(function(){
            var currId = parseInt($(this).attr("id"));
            lastLi = $(this);
            if (currId > id){
                el.insertBefore($(this));
                lastLi=null;
                return false;
            }
        });

        if (lastLi){
            el.insertAfter(lastLi);
        }
    });
});​
+1

, , , ... , jQuery wrap http://api.jquery.com/wrap/

, ...

0

All Articles