Jeff Thomas
Jeff Thomas

Reputation: 4816

Detecting .click() from ajax loaded element

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?

Upvotes: 1

Views: 695

Answers (3)

academo
academo

Reputation: 142

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

Upvotes: 3

Aqib1604
Aqib1604

Reputation: 302

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

$(document).on('click', 'button#submit', function(){

alert("hi");
});

Upvotes: 0

Software Engineer
Software Engineer

Reputation: 16120

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.

Upvotes: 0

Related Questions