Reputation: 347
I have a PHP application, which has a delete function on one of the pages. I am allowing user to delete a tag from their profile, by clicking on the tag. Once the user clicks the tag, the content area in the HTML which previous displayed the tags, gets updated with the new set of tags.
Now the problem is, from the list of tags,the first time user clicks a tag, it is deleted.If the user now clicks another tag(from the refreshed area), nothing happens.
$("a.single_tag").click(function(){
the_id = $(this).attr('id');
$.ajax({
type: "POST",
data: "data="+the_id,
url: "<?php echo site_url('user/deletetag/');?>/",
success: function(msg)
{
$("#current_tags").fadeIn("slow");
$("#current_tags").html(msg);
}
});
Thanks
Upvotes: 0
Views: 648
Reputation: 24472
This is because new html tags that you just received from the server, did not have your "delete" function bound to them on click.
Upvotes: 0
Reputation: 4336
You need to throw that chunk of binding code in a function, and call it in the success callback, or only update the HTML of the updated tags (that is, return an id to delete, or a block of html to append, instead of redisplaying the whole block).
When you update the content, the .click
binding does not exist on the new a
tags.
Edit: @Nick Craver's solution is much better.
Upvotes: 0
Reputation: 630489
Instead of using .click()
for this, you want .live('click', func)
, like this:
$("a.single_tag").live('click', function() {
When you use .click()
you're binding a click
handler to those elements, but when the content gets replaced, new elements with no handlers are there. With .live()
it listens for the click
event when it bubbles to document
and executes...whether the element was there when the page loaded or added later, it won't matter...fixing your issue :)
Upvotes: 5