1

I'm trying to delete one of the items which are generated by entering text and clicking the "add another" link in the linked example, but the jquery does not trigger from the generated content. If I attach the event handler to another object the function triggers but not from the generated links, any way to fix this? In the code below; when the user clicks a link with the class delLink I want the surrounding div of that link and all elements in that div removed (erased).

<div class="regItm">
    <input properties...><a class="delLink" properties...>X</a>
</div>
<div class="regItm">
    <input properties...><a class="delLink" properties...>X</a>
</div>
...
...

http://jsfiddle.net/KYkJn/2/

1
  • solved it with the code of nrodic, thx! Commented Oct 23, 2012 at 23:14

3 Answers 3

3

Try this:

$('.delLink').live('click', function(){
    alert('ohoy');
    $(this).closest('div').remove();
});

Since you're dynamically adding items to the DOM, your current functions (at the state of page load) don't apply to them.

To get around that, there's the live() function. This ensures that current and future selectors in the DOM can be handled.

Sign up to request clarification or add additional context in comments.

3 Comments

Nice .. Most forget about the .live() making sure dynamic elements get added to the DOM
That's it. But because of "As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers." I would reccomend $("#basket").on("click", ".delLink", function() {
Oh wow, I didn't notice the deprecated tag on live. Will transition my old code to on() :). Edit: Apparently, .live() is now just an alias of .on().
1

http://jsfiddle.net/Cz4Cy/

 $('body').on('click', '.delLink', function() {
     alert('ohoy');
     $(this).closest('div').remove();
 });

You should use event delegation for such cases. This will allow you to add event handlers for elements that does not exist yet.

http://api.jquery.com/on/


Code above is for illustrative purposes only. You should avoid adding delegated event listeners on body, document or window. Add them to your container, instead.

Comments

0

You bind your event at the moment when script is executed and your basket is actually empty.

Recommended way to do such events binding with dynamic content is to use on() and off() methods on the parent element:

$('#basket').on('click', '.delLink', function(e) {
   alert('ohoy');
   $(this).closest('div').remove();
   e.preventDefault();
   return false; 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.