Daniel C Daniel C - 1 year ago 93
jQuery Question

Javascript function on a button generated after an onclick event of another button

I have a script where a user can press a button which makes an AJAX call. Once the call is completed, the button is replaced with text saying "Complete" as well as a new button called "Undo". The purpose is to allow the user to undo the action they just took:

<script type="text/javascript">
$('button').on('click', function() {
ajax call
update.append('Complete<button type=\"button\" id=\"undo\">Undo</button>');

However, I am having trouble making the Undo button connect to the onclick function for that id. Actually, nothing seems to happen when I click the Undo button.. I believe it may have to do with the undo button having been generated within an update.append from the onclick function above.. However, I am having trouble understanding what is going wrong. Here is my function for the undo click event for a button with id=undo (which was added in the original onclick function above):

$("#undo").click(function() {
ajax call

I placed this function just below the first function in my script, but nothing happens when I press the Undo button. Even if I add an alert within the function for testing, the alert doesn't even show.

Any suggestions would be much appreciated.

Answer Source

$("#undo").click will only work if the element was not added dynamically to the DOM. Since you are dynamically adding undo use .on instead:

$('body').on('click', '#undo', function() {
    ajax call
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download