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?

Jeff Thomas
  • 4,728
  • 11
  • 38
  • 57
  • Why are you selecting `"button#submit"`? Why not just select `"#submit"`? – Muntaser Ahmed Oct 02 '14 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. – beaglebets Oct 02 '14 at 21:38
  • See http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Jasen Oct 02 '14 at 21:41

3 Answers3

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

academo
  • 118
  • 6
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.

Software Engineer
  • 15,457
  • 7
  • 74
  • 102
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");
});
Aqib1604
  • 292
  • 1
  • 7
  • 1
    There is no difference between .on and .click – Frederik Witte Oct 02 '14 at 21:39
  • 1
    http://stackoverflow.com/questions/6658752/jquery-click-event-doesnt-work-on-dynamically-generated-elements check the answer you have to use .on() for dynamically added element thats the difference – Aqib1604 Oct 02 '14 at 21:47