0

I have a file 'controlpanel.php' that uses jQuery and communicates to another php file through AJAX Get requests. That ajax request will result in a table with some buttons being displayed in controlpanel.php

$(document).ready() is only called once, and it is called before the table is loaded (from the AJAX request).

How can I use jQuery to watch mouse handlers for the newly loaded table (aka after $(document).ready() has been called?

Specifically, I am trying to do something like:

$('[id^=modify-btn]').click(
    function () { 
        alert("modify-btn !!");
        //and other fun stuff
    }
    );

AFTER the AJAX request goes through, but I am unsure as to how to enable this trigger.

Thank you for your time!

Michael Shum
  • 681
  • 1
  • 5
  • 8

1 Answers1

2

You can use on() for event binding on dynamically created elements (loaded content through AJAX).

$(document).on( eventName, selector, function(){} );

So you can implement it like this:

$(document).on('click', '[id^=modify-btn]',
    function () { 
        alert("modify-btn !!");
        //and other fun stuff
    }
);
chris97ong
  • 6,267
  • 6
  • 28
  • 48
  • Beat me to it. :p – Morgan Green Sep 17 '16 at 02:37
  • Hi guys, shortly after posting, I tried adding the code to the callback of the AJAX get command. Is this also okay? It seems to be working as of right now, but maybe you guys know something that may comeup down the line. Thanks! – Michael Shum Sep 17 '16 at 04:05
  • @MichaelShum You can add it directly under `$(document).ready` (not in the AJAX callback). – chris97ong Sep 17 '16 at 04:28
  • Sorry I didn't specify - I meant my original code, not your code. Would adding my code to the callback cause any issues later, or is it just as valid as your code? I understand it's good to keep all button handling in the same area – Michael Shum Sep 17 '16 at 05:04
  • @MichaelShum I think (can't be sure though) if you include your original code to the AJAX callback function, it will bind the event to **every** of those elements each time a new one loads. In other words, you might end up triggering multiple of the same events when one element is clicked. – chris97ong Sep 17 '16 at 10:44
  • If you put my code directly inside the `$(document).ready` function, it will definitely work and likely be most performant – chris97ong Sep 17 '16 at 10:45
  • Thanks so much!! :D – Michael Shum Sep 18 '16 at 02:53