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

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');
});

Leave a Comment