0

I am creating some a tag dynamically. Then I am trying to attach click event with them. But those events are not firing.

Here is my code:

$(function() {
    onUploadReady();
});

var onUploadReady = function() {
    $('a[name=add]').on('click', function(event){
        event.stopPropagation();
        $('table#multiUpload').append('<tr><td style=\"text-align: center;\"><input type=\"file\" name=\"file\"/></td><td><a href="#" name="remove">Remove</a></td></tr>');
        return false;
    });

    $('a[name=remove]').on('click', function(event){
       event.stopPropagation();
       $(this).parents('tr').eq(0).remove(); 
       return false;
    });
}

If I do $('a[name=remove]').live('click', function(event) instead of $('a[name=remove]').on('click', function(event), then the event is firing. I read somewhere that usage of live is discouraged, and we should use on. Also event propagation or bubbling can occur if we use live. So how do I solve the issue?

jsFiddle.

Tapas Bose
  • 28,796
  • 74
  • 215
  • 331

2 Answers2

3

Do it like:

$("parent_selector").on('click', 'a[name=remove]', function(e){
   //do something
})

If parent_selector is not known, use document instead.

In your example, you can write:

$("table#multiUpload").on('click', 'a[name=remove]', function(e){
   //do something
})

The syntax you are using is just like bind. For dynamically added elements you should use the above syntax. In this we attach the handler to parent which already exists, instead of newly added element. So it will work for all elements added in future.

Arvind Bhardwaj
  • 5,231
  • 5
  • 35
  • 49
2

use:

$(document).on('click', 'a[name=remove]', function(e){
...
});
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
  • this really helped me, thank you. i was having an issue where Google Analytics would not register my onclick trackEvent call when I changed the attibute with jQuery. Changed my function syntax to the above and it worked. Thanks! – surfbird0713 Aug 13 '13 at 21:13