Crystallize Crystallize - 1 year ago 65
HTML Question

Binding Jquery event to a button in an Async event response

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.

Answer Source

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>

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 and the section called "Direct and delegated events" for a fuller explanation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download