Christopher Wilke
Christopher Wilke

Reputation: 65

Cannot access jQuery when appending

I append a button via jQuery.

$('#toAppend').html('<input type="button" id="helloWorld">');

In my browser, I can see the button but I am not able to access it via jQuery.

Code:

$('#helloWorld').click(function () {
    alert("you clicked me");
})

Any help is appreciated.

Thanks.

Upvotes: 1

Views: 43

Answers (2)

Nonemoticoner
Nonemoticoner

Reputation: 648

You have to access it in a different manner because it was appended to html after the page was loaded:

$("#toAppend").on("click", "button#helloWorld", function(e) {
    console.log("clicked!");
});

Upvotes: 2

Abhishekh Gupta
Abhishekh Gupta

Reputation: 6236

Use on() like this for Event Delegation:

$(document).on('click', '#helloWorld', function () {
  alert("you clicked me");
})

Upvotes: 2

Related Questions