My application adds new posts to an <ul> using .prepend() and then uses the .ajax() function to add it to the database like so:
$("#add input[type=submit]").click(function(){
newPost = $("#add textarea").val();
$.ajax({
type : "POST",
url : "/add",
data : { "post" : newPost },
success: function(data) {
$('#posts ul').prepend('<li id="1234"><p>'+newPost+'<p><span class="delete">Delete</span></li>');
}
});
This works as intended, but as you can see I have a Delete button for each post and I delete post using the following jquery:
$(".delete").click(function(){
var thiscache = $(this),
post_id = thiscache.closest("li").find("p").attr("id");
$.ajax({
type : "POST",
url : "/delete",
data : { "post_id" : post_id },
success : function(r){
thiscache.parent().slideUp('slow');
},
});
});
Delete will work with post that have been added previously, but if you add a post using the ajax form, and click delete nothing fires. What could be the cause of this? Maybe the new post <li> isn’t in the DOM?
I created a JSfiddle without the Ajax functions. http://jsfiddle.net/bhhgf
If you add a new post it will append it, but you can not delete it. Deleting the current posting works just fine.
EDIT:
I also use jeditable with a custom event, but .live() will not tigger new post.
$("p").editable('/edit/save', {event : 'edit_button'});
$(".edit").live('click', function(){
$(this).closest("li").find("p").trigger('edit_button');
});
for the dynamically added elements to the DOM you need to rebind the event handler to them or use
.liveor.delegateor
jquery livejquery delegatefor the
editlink in your firstajaxcallback again call thejeditableon the desired elements