Nick Nick - 7 months ago 17
Javascript Question

jQuery .on('change', function() {} not triggering for dynamically created inputs

The problem is that I have some dynamically created sets of input tags and I also have a function that is meant to trigger any time an input value is changed.

$('input').on('change', function() {
// Does some stuff and logs the event to the console
});


However the
.on('change')
is not triggering for any dynamically created inputs, only for items that were present when the page was loaded. Unfortunately this leaves me in a bit of a bind as
.on
is meant to be the replacement for
.live()
and
.delegate()
all of which are wrappers for
.bind()
:/

Has anyone else had this problem or know of a solution?

Answer

You should provide a selector to the on function:

$(document).on('change', 'input', function() {
  // Does some stuff and logs the event to the console
});

In that case, it will work as you expected. Also, it is better to specify some element instead of document.

Read this article for better understanding: http://elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/