Tito
Tito

Reputation: 9044

Jquery click event not firing on previously hidden div

I am loading a 'password-reset-success-message' div into a 'password-reset' div dynamically as shown in the below snippet.The 'password-reset-success-message' div is hidden on page load and is overwritten to the 'password-reset' div as shown below.

    $("#password-reset").html($("#password-reset-success-message").html());

Now the 'password-reset-success-message' div has a 'btnPasswordResetOK' button which will close the password reset modal dialog.But this click() event is not getting binded. I am not getting the alert message. I am doing all of this wrapped inside the document ready.

     $(document).ready(function(){  

       $("#btnPasswordResetOK").click(function() {

         alert();
       });

    });

Note: This question is almost similar to my question..but there are not answers for it.

UPDATE : I binded after updating the html with the hidden div and it works ! , code snippet below

      $("#password-reset").html($("#password-reset-success-message").html());

       $("#btnPasswordResetOK").click(function() {

            alert();
       });

Upvotes: 0

Views: 9438

Answers (2)

wirey00
wirey00

Reputation: 33661

delegate it to the parent element you are adding the html to

if using jQuery 1.7+ with .on()

$("#password-reset").on('click','#btnPasswordResetOK',function(){

})

with delegate

$("#password-reset").delegate('#btnPasswordResetOK','click',function(){

})

From jQuery docs on which method to use

$(selector).live(events, data, handler); // jQuery 1.3+

$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+

$(document).on(events, selector, data, handler); // jQuery 1.7+

By delegating, you bind the event handler to a static parent element that doesn't change and exists at the time of binding. You specify the element and the events you want to listen to, and when the event bubbles up it will get handled by the static parent element.

Upvotes: 3

Learner
Learner

Reputation: 4004

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

Your content is not there on the page when ready event is triggered. You generate the elements and content dynamically so you must use live/on event handler.

Upvotes: 1

Related Questions