0

With a JQuery GET request, I'm generating Google Authenticator secret (this part works fine). After the Secret has been generated, I'm hiding the generated ID and display the one time password for submit. Inside the one time password, I have a button. Now I do a simple alert to test the button but this button is not working. Can anyone let me know what I'm doing wrong in my JQuery script:

$( "#enable_authenticator" ).click(function() {
    $.get("{{route('generateSecret')}}",
    function(data, status){
        $('#Authenticator_alert').hide();
        $('#enable_authenticator').hide();
        $( "#set_authenticator" ).html('<center>'+data[0]+'<br>'+'Your Authenticator Secret is: <strong>'+data[1]+'</strong> <br> <input type="text" placeholder="One Time Password" id="onetimepassword" class="form-control"><br> <button type="button" id="submitOneTimePassword" class="btn btn-warning">Submit</button></center>');
    });
});

$('#submitOneTimePassword').click(function() {
    alert('here');
});

ID: submitOneTimePassword is not working.

user1280483
  • 470
  • 4
  • 11
masternode
  • 61
  • 1
  • 4
  • From this amount of code, the `$(...).click()` event looks correct. Could you add more from the HTML, so we can get a better picture of this? – charlie-map Nov 28 '21 at 23:15
  • `$('#submitOneTimePassword').on('click', function(...` – pavel Nov 28 '21 at 23:18
  • @pavel That is effectively no different than what OP is already using with the shortcut method `.click()`. That selector does not exist at run time – charlietfl Nov 28 '21 at 23:33

1 Answers1

2

That is because your element with the ID submitOneTimePassword is not present at runtime. Use event delegation instead (i.e. using .on()), so that you capture the click event bubbling from the dynamically added element. Since the parent #set_authenticator is already present at runtime, you can listen to the bubbled up click event from it instead:

$('#set_authenticator').on('click', '#submitOneTimePassword', function() {
    console.log('clicked');
});
Terry
  • 63,248
  • 15
  • 96
  • 118