Nick
Nick

Reputation: 1937

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?

Upvotes: 186

Views: 687241

Answers (8)

Arsman Ahmad
Arsman Ahmad

Reputation: 2211

You can use any one of several approaches:

$("#Input_Id").change(function(){   // 1st way
    // do your code here
    // Use this when your element is already rendered
});


$("#Input_Id").on('change', function(){    // 2nd way
    // do your code here
    // This will specifically call onChange of your element
});

$("body").on('change', '#Input_Id', function(){    // 3rd way
    // do your code here
    // It will filter the element "Input_Id" from the "body" and apply "onChange effect" on it
});

Upvotes: 39

Yehia Fouad
Yehia Fouad

Reputation: 51

you can use:

$('body').ready(function(){
   $(document).on('change', '#elemID', function(){
      // do something
   });
});

It works with me.

Upvotes: 4

Alex
Alex

Reputation: 9720

You can use 'input' event, that occurs when an element gets user input.

$(document).on('input', '#input_id', function() {
  // this will fire all possible change actions
});

documentation from w3

Upvotes: 3

Vinod Kumar
Vinod Kumar

Reputation: 1311

$(document).on('change', '#id', aFunc);

function aFunc() {
  // code here...
}

Upvotes: 2

dynero
dynero

Reputation: 300

Just to clarify some potential confusion. This only works when an element is present on DOM load:

$("#target").change(function(){
    //does some stuff;
});

When an element is dynamically loaded in later you can use:

$(".parent-element").on('change', '#target', function(){
   //does some stuff;
});

Upvotes: 9

Dixon
Dixon

Reputation: 375

Use this

$('body').on('change', '#id', function() {
  // Action goes here.
});

Upvotes: 31

Azhar
Azhar

Reputation: 97

$("#id").change(function(){
    //does some stuff;
});

Upvotes: 4

Artem Vyshniakov
Artem Vyshniakov

Reputation: 16465

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/

Upvotes: 327

Related Questions