Click handler not called by dynamically generated element

After submitting the form (using ajax) I try to extinguish it and give the user a message, and the link gives the user the opportunity to display the form again.

After submitting the form ....

$(form).animate({ opacity: 0.0}, 500, function(){ $(this).fadeOut(400); $(".success-msg") .prepend('<h1> Success! You submitted a quote! </h1> <a class="quote-link" href="/quote-' + id + '"> localhost.com/quote-' + id + ' </a> <a class="goback" href="#"> Or click here to submit another quote </a>') .fadeIn(500); 

And if they want to return, they will .goback on .goback , which will hide the .success-msg box .

 $('.goback').click(function(){ $(this).parent().fadeOut(500).hide().empty(); $('#submit-quote').animate({opacity: 1}, 500).fadeIn(500); }); 

The problem is that if they click ..

 <a class="goback" href="#"> Or click here to submit another quote </a> 

after joining dom, the click event does not work. But if I put it in the default .success-msg field and add only other HTML. It will work. But then, if they return to the form and submit another quote, then .empty () will free the item and therefore .goback no longer exists.

How can I do this job?

+4
source share
3 answers
 $(".success-msg").on('click','.goback',function(){ $(this).parent().fadeOut(500).hide().empty(); $('#submit-quote').animate({opacity: 1}, 500).fadeIn(500); }); 

or if you are not using jQuery 1.7 or later ...

 $(".success-msg").delegate('.goback','click',function(){ $(this).parent().fadeOut(500).hide().empty(); $('#submit-quote').animate({opacity: 1}, 500).fadeIn(500); }); 
+4
source

Use delegate or on because you control dynamically.

Using Delegate

  $(document).delegate('.goback', 'click', function(){ $(this).parent().fadeOut(500).hide().empty(); $('#submit-quote').animate({opacity: 1}, 500).fadeIn(500); }); 

Using on if you are using jQuery 1.7+

  $(document).on('click', '.goback', function(){ $(this).parent().fadeOut(500).hide().empty(); $('#submit-quote').animate({opacity: 1}, 500).fadeIn(500); }); 
+3
source

A handler is assigned before an element exists. Try using the live function, namely:

 $('.goback').live('click', function(){ $(this).parent().fadeOut(500).hide().empty(); $('#submit-quote').animate({opacity: 1}, 500).fadeIn(500); }); 

This will assign the onclick handler when the item appears in the DOM.

-1
source

Source: https://habr.com/ru/post/1391142/


All Articles