user544079
user544079

Reputation: 16629

jQuery detect events of dynamically added elements

I have a table

<table id="table1">
   <tbody>
   <tr>
     <td></td>
     <td><input type="text" /></td>
  </tr>
  </tbody>
</table>

A new row is added when enter is pressed on the input box

$('[type=text]').on('keyup', function(e){
    if(e.keyCode == 13){
        var newRow = '<tr><td></td><td><input type="text" /></td></tr>';
        $('#table1 tbody tr').last().after(newRow);
    }
});

It works fine for the 1st row. However, any event on the dynamically added newRow is not detected.

How can this be fixed?

Upvotes: 0

Views: 44

Answers (5)

Academia
Academia

Reputation: 4124

You simply change on() with live(), in jQuery<=1.7, like this:

$(selector).live( eventName, function(){} );

Which is:

$('[type=text]').live('keyup', function(e){
    if(e.keyCode == 13){
        var newRow = '<tr><td></td><td><input type="text" /></td></tr>';
        $('#table1 tbody tr').last().after(newRow);
    }
});

Or, in jQuery>1.7, better use:

$(staticAncestors).on(eventName, dynamicChild, function() {});

So:

 $('#table1').on('keyup', '[type=text]', function(e){
        if(e.keyCode == 13){
            var newRow = '<tr><td></td><td><input type="text" /></td></tr>';
        $('#table1 tbody tr').last().after(newRow);
    }
 });

Hope it's useful!

Upvotes: 0

BadZen
BadZen

Reputation: 4265

Another method different from the ones presented here so far is to attach the error handler to the newly created element in the keypress handler...

Upvotes: -1

giorgio
giorgio

Reputation: 10202

You can attach the handler on an element further up the DOM, and then filter it. Checkout the documentation for all info. But in your case, this should work:

$('#table1').on('keyup', '[type="text"]', function(e) {
    // your code
});

Whenever attaching the event to a parent element, please make sure to choose the lowest element possible. Attaching to document is usually a bad idea, as you'll get a performance penalty (because the handler will be fired anytime a key is hit, not somewhere in the DOM element you selected...).

Upvotes: 1

Yogesh
Yogesh

Reputation: 3482

You can attach event to parent element which exists on the page. Read more about event delegation.

$('#table1').on('keyup', '[type=text]', function(e){

 });

Upvotes: 1

Kiran
Kiran

Reputation: 20313

You can't set a click handler on an element that doesn't exist. You should use event delegation. Try this:

$("#table1").on('keyup','[type=text]', function(e){
    if(e.keyCode == 13){
        var newRow = '<tr><td></td><td><input type="text" /></td></tr>';
        $('#table1 tbody tr').last().after(newRow);
    }
});

DEMO

Upvotes: 0

Related Questions