1

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.

Henrik Petterson
  • 6,737
  • 17
  • 59
  • 134
  • Binding event listeners to the `document` or `body` is bad practice. – Ron van der Heijden Jul 10 '18 at 12:57
  • 2
    @RonvanderHeijden not really, it's the standard way to handle event binding for dynamically added elements: https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – freedomn-m Jul 10 '18 at 12:59
  • Can you include your html? Does the code work if it's *not* added dynamically? Do you have any other event handlers? `onclick=`/`onsubmit=` inline handlers? – freedomn-m Jul 10 '18 at 13:00
  • try this $('.comment-form', body).on('submit',function(){}); – Parth Shah Jul 10 '18 at 13:02
  • @ParthShah that won't work for dynamically added elements (ie elements added after the js has been called) – freedomn-m Jul 10 '18 at 13:02
  • 1
    @freedomn-m The code works fine when it is *not* added dynamically. And no other inline handlers. – Henrik Petterson Jul 10 '18 at 13:07
  • @freedomn-m No it's not, even your reference says `Though bear in mind document may not be the most efficient option.` Binding to a parent element that is available is much better. Also read: https://stackoverflow.com/questions/12824549/should-all-jquery-events-be-bound-to-document – Ron van der Heijden Jul 10 '18 at 14:34
  • @RonvanderHeijden agreed. But "not the most efficient" and "bad practice" are not the same thing. Depends on the scenario. – freedomn-m Jul 10 '18 at 14:35

2 Answers2

1

Try it

jQuery(function($){
   $(body).on('submit', '.comment-form',function(){
      // do stuff
   });
});
Rohit Verma
  • 2,571
  • 3
  • 21
  • 42
  • 1
    There's no real difference between using `body` vs `document` - as long as the element in the `$()` exists when called and the new element is added within that element. – freedomn-m Jul 10 '18 at 13:02
0

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>
DsRaj
  • 2,122
  • 1
  • 13
  • 24