JD Isaacks
JD Isaacks

Reputation: 58004

JQuery doesn't apply to elements created after page load

If I call this:

$(".month-selector").change(function(){
    setStones();
});

Inside the$(document).ready() it does not apply to elements that are created later. I also tried calling the above code after creating them like so:

$("#month-selectors").html(month_selectors);

$(".month-selector").change(function(){
    setStones();
});

It still doesn't work. However, If I create a static one, it works.

How can I apply this to the elements when I create them after the page loads?

Upvotes: 1

Views: 3379

Answers (3)

Siddharth Bhansali
Siddharth Bhansali

Reputation: 21

That was super helpful! However, on in case you are adding an input event after the DOM has loaded you will need to use the "click" event to get it to work:

  $("input#thename").live("click", function(event) {
// handler for what should happen when somebody clicks on the new input field, in this case I needed a datepicker to pop up so lets get that fired. Now that the click element registered the new input object with the DOM, it can be used like a normal jQuery selector!
    $("input#thename").datepicker();
    });

Upvotes: 2

zerodin
zerodin

Reputation: 877

try:

$(".month-selector").live("change", function(event) {
 // some code
});

Upvotes: 0

Brian Flanagan
Brian Flanagan

Reputation: 4642

You can use jQuery's 'live()' method to add event listeners to current and future nodes.

$(".month-selector").live('change', function(){
    setStones();
});

Upvotes: 14

Related Questions