I'm creating a dynamic event calendar list, and I'm trying to figure out a way to add a new element between two elements based on their Ids. The existing elements have a ID that is formatted to be use as the date of the event.
The ID's are created by the date yymmdd
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 to dynamic create a new event and place it in the correct spot. For example: If the user creates another event for May 24th, 2012, it should be placed between the two about li's.
It would have to be dymanic, because if there were ton's of events in the list, only one event per day, it would have to grab the first element that's ID is greater than it, and the first element that's ID is less than it, and create the new element in between them.
Example:
I'm trying to generate something like this:
<li id="120504">May 4, 2012<li>
and place it in the correct order by id into an unordered-list like this:
<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>
using jQuery
Try this: 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);
}
});
});
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