0

I am creating a form with a dynamic number of options. Deleting options works fine for those items that are existing from the start, but the items that are generated dynamically cannot be removed. Anyone have a clue?

JSFiddle: http://jsfiddle.net/Kxr4C/

HTML:

<div class="options">
  <div><input type="text" name="option[]" value="Option A"> <a href="#" class="delete_option">Delete</a></div>
  <div><input type="text" name="option[]" value="Option B"> <a href="#" class="delete_option">Delete</a></div>
  <div><input type="text" name="option[]" value="Option C"> <a href="#" class="delete_option">Delete</a></div>
</div>
<a href="#" class="new_option">Add a new option</a>

Javascript:

jQuery('a.new_option').click(function(){
  jQuery('div.options').append('<div><input type="text" name="option[]" value=""> <a href="#" class="delete_option">Delete</a></div>');
});

jQuery('a.delete_option').click(function(){
  jQuery(this).parent('div').fadeOut();
});
dirk
  • 1,854
  • 3
  • 18
  • 28
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – t.niese Jan 20 '14 at 16:07

3 Answers3

3

You need to use event delegation for dynamically created element:

jQuery('div.options').on('click', 'a.delete_option', function(){
  jQuery(this).parent('div').fadeOut();
})
Felix
  • 36,929
  • 7
  • 39
  • 54
0

Use .on()

jQuery.on('click', 'a.delete_option', function () {
    jQuery(this).parent('div').fadeOut();
});

Event Delegation

Tushar Gupta - curioustushar
  • 54,013
  • 22
  • 95
  • 103
0

you should use .on method instead so that it delegates the event on new elements.

jQuery(document).on('click','a.delete_option',function(){
jQuery(this).parent('div').fadeOut();
});

here's a new fiddle http://jsfiddle.net/rjC6C/

Marcelo Biffara
  • 771
  • 3
  • 7
  • 1
    While this is the correct syntax for delegate, `.on` on itself does not mean _delegate_. [`[...]As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.[...]`](http://api.jquery.com/on/) so `.on` it is the preferred way of adding _direct_ and _delegate_ listeners, only adding the selector as second argument makes it to a _delegate_. – t.niese Jan 20 '14 at 16:15