0

I have a select which runs an AJAX function. This function returns a form with a button. Now I'd like to assign a function to this button with jQuery's .click() (or .on()).

E.g.

<select id='test'>
    <option val='1'>...</option>
    ...
</select>

/* Empty and filled with AJAX call */
<div id="ajax">
     /* FOLLOWING THE CONTENT RETURNED BY THE AJAX CALL */
     /* Won't work (see script below) */
     <input type="button" id="button" value="button" />

     /* will work */
     <input type="button" value="button" onclick="clickMe()" />
</div>

JavaScript

$('#test').change(function(){
    $.ajax({
        ...
});

$('#button').click(function(){
    /* DOESN'T WORK */
    alert('click')
});

function clickMe(){
    /* WORKS */
    alert('click')
};

Is there a way to "enable" the AJAX result?

Perocat
  • 1,481
  • 7
  • 25
  • 48
  • https://api.jquery.com/on/ and scroll where it talks about **Direct and delegated events** and the *Delegated Events* example with `TR` – Roko C. Buljan Feb 24 '14 at 01:18
  • possible duplicate of [jQuery - Click event doesn't work on dynamically generated elements](http://stackoverflow.com/questions/6658752/jquery-click-event-doesnt-work-on-dynamically-generated-elements) – jprofitt Feb 24 '14 at 01:22

4 Answers4

3

You need to use event delegation method, since the buttons are created dynamically . You can use jQuery on() method to listen the button.

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

Otherwise the event doesn't bind to the dynamically generated item.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
2

I agree with @Pranav C Balan, that is a way to solve the problem. And I propose another way: after the ajax response, you can bind the event in the added markup. Like:

$.get("test.jsp",function(response){
    $("#ajax").children("#button").click(function(){
       // click callback goes here...
    });
},"html")

Tips: do not nest the callback more two func. That will make the spaghetti code.To solve this you can use the promise in jquery. Here is the doc. (JXHR object)

Tyler.z.yang
  • 2,402
  • 1
  • 18
  • 31
1

Assign the event to highest element before the dynamic form using the .on() function with a selector that matches your button(s).

This will attached the event to all current and future matching elements.

$("#ajax").on("click", "#myButtonId", function(){
    // On click code here.
});
Timeout
  • 7,759
  • 26
  • 38
0

you should use jQuery's .on() to listen for the event bubbling to the parent element. This means it will still fire the event for elements that are added after you have set the event listener.

$('#ajax').on('click','#button',function(){
    alert('click');
});

See the jQuery documentation for on: http://api.jquery.com/on/

Bill
  • 3,478
  • 23
  • 42