Henrik Petterson
Henrik Petterson

Reputation: 7094

.on() not working on dynamically added element

I have the following code:

jQuery(function($){
   $( '.comment-form' ).submit(function(){
      // do stuff
   });
});

I want to target this element when it has been added dynamically. So I use:

jQuery(function($){
   $(document).on('submit', '.comment-form',function(){
      // do stuff
   });
});

But the event trigger is never added when the element is created dynamically. Is there an issue with the following:

$(document).on('submit', '.comment-form',function(){

As far as I can see, this is correct.

Upvotes: 1

Views: 229

Answers (2)

DsRaj
DsRaj

Reputation: 2328

Check this and update your code as needed

$(".add_new").click(function(){
  $(".form_area").html('<form class="main_form"><input type="submit" value="submit"></form>');
});
$(document).on('submit','.main_form',function(){
  alert('Form submit');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><button class="add_new"> Add New Form </button></div>
<div class="form_area">
  <!--For dynamic added content-->
</div>

Upvotes: 0

Rohit Verma
Rohit Verma

Reputation: 3785

Try it

jQuery(function($){
   $(body).on('submit', '.comment-form',function(){
      // do stuff
   });
});

Upvotes: 1

Related Questions