1

I have a button that is loaded into my page using ajax:

<button id="submit">Submit</button> 

I am using this code on the page that the button is being loaded into:

<script type="text/javascript"> $(function() { $("button#submit").click(function(){ alert('Submit Clicked'); }); }); </script> 

Why is it not detecting the click from the ajax content?

3
  • Why are you selecting "button#submit"? Why not just select "#submit"? Commented Oct 2, 2014 at 21:37
  • 1
    You're listening for something that isn't on the page yet. You need to use event delegation. Set the listener for a parent element that is already on the page when it loads initially. Commented Oct 2, 2014 at 21:38
  • See stackoverflow.com/questions/203198/… Commented Oct 2, 2014 at 21:41

3 Answers 3

3

When you attach the click event you attach it to the existent elements in the DOM, when the ajax content comes, new DOM elements are created and the event wasn't attached to them.

One option is to use events delegation a way (but not recommended) to do it is using the document to read the event

$(document).on('click', 'button#submit', function(){ //do something }); 

A better way is put the delegation to the element which gets the new content, lets assume is a form with an id formElement, It would be something like

$("#formElement").on('click', 'button#submit', function(){ //do something }); 

Using that event delegation the new content from ajax will fire the click event.

PD if you have an ID in a element just use the id, like #submit, It makes a faster selector than tag#id because It used getElementById internaly

Sign up to request clarification or add additional context in comments.

Comments

0

In your code you have attached the event handler to buttons before the button is created. You need to attach the handler afterwards. Add the handler in the ajax success() function instead, after you have created the button, and everything will work ok.

Comments

0

Its because its dynamically added button.For that you have to use on() method try following

$(document).on('click', 'button#submit', function(){ alert("hi"); });

2 Comments

There is no difference between .on and .click
stackoverflow.com/questions/6658752/… check the answer you have to use .on() for dynamically added element thats the difference

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.