0

I have a page that sends an asyncronous Jquery request to another page, and i receive a button in response. Button has class "delete_button".

<BUTTON class="delete_button">Delete</BUTTON>

The problem is, this "new" button is not bound (and doesn't trigger) any Jquery event.

I've tried to use the .on() function (And the old deprecated .live()) but i couldn't bind an event to that button. The Jquery even is as follows.

$(".delete_button").on("click", function(){
  //Code here...
});     

I've checked using a debugger that the button actually has the correct class, and the Javascript signals no error. Nothing strange in the console. Simply, the event does not occur.

Crystallize
  • 110
  • 1
  • 11
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – vijayP Jul 12 '16 at 10:23

1 Answers1

1

Let's say when you receive your delete_button that it gets appended to a div, so that it's within that div, e.g.

<div id="myDiv">
  <button class="delete_button">Delete</button>
</div>

Knowing this, you can create an on event like this:

$("#myDiv").on("click", ".delete_button", function(){
  //Code here...
}); 

That way the event is bound to an element which definitely exists, and then jQuery delegates that event to any dynamically created elements with the .delete_button selector.

The way you're doing it currently, it doesn't matter that you use .on, because the initial selector (in the $("selector")) part has to be something that exists when the page loads. See http://api.jquery.com/on/ and the section called "Direct and delegated events" for a fuller explanation.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • It worked perfectly, all new buttons that get created withing that div are bound correctly and trigger events. Thanks, this was exactly what i was looking for. – Crystallize Jul 12 '16 at 10:32