Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Events triggered by dynamically generated element are not captured by event handler

I have a <div> with id="modal" generated dynamically with the jQuery load() method:

$('#modal').load('handlers/word.edit.php'); 

word.edit.php contains a few input element, which are loaded into a modal <div>.

Using jQuery's keyup method I can capture the input values after an event fires, but when the elements are added dynamically to the modal div, the event no llonger fires when the user enters their text.

Which jQuery method supports handling events triggered by dynamically created elements?

The code for creating the new input elements is:

$('#add').click(function() {     $('<input id="'+i+'" type="text" name="translations' + i + '"  />')       .appendTo('#modal'); 

The code for capturing the user's values is:

$('input').keyup(function() {     handler = $(this).val();     name = $(this).attr('name'); 

This second code block seems to work for the original elements, but it is not fired by the new dynamically generated elements.

like image 974
redbull330 Avatar asked Oct 10 '12 23:10

redbull330


1 Answers

You need to delegate the event to the closest static ancestor element within the page (see also "Understanding Event Delegation"). This simply means, the element where you bind your event handler must already exist at the time the handler is bound, so for dynamically generated elements you must allow the event to bubble up and handle it further up.

The jQuery .on method is the way to do this (or .delegate for older versions of jQuery.)

// If version 1.7 or above  $('#modal').on('keyup', 'input', function() {     handler = $(this).val();     name = $(this).attr('name'); }); 

Or in older versions

// If version 1.6 or below  // note the selector and event are in a different order than above $('#modal').delegate('input', 'keyup', function() {     handler = $(this).val();     name = $(this).attr('name'); }); 
like image 153
Sushanth -- Avatar answered Oct 04 '22 20:10

Sushanth --