2

I've got a button on my page that allows a user to add a form. When a button within the new form is clicked, a jquery function should run. Unfortunately, the jquery function doesn't seem to run on the newly appended divs (it does run divs that existed on initial page load).

<div id="empty_form" style="display:none">

    <!-- Form Contents --> 

    <div class="deletebox">
        Remove
    </div>
</div>

<div id='add_more'>
    Add Another Form
</div>


<script>
   $('#add_more').click(function() {
       var form_idx = $('#id_form-TOTAL_FORMS').val();                
       $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
    });
</script>

<script>   
    $(".deletebox").click(function () {
        console.log('box was clicked')
    });
</script>

When the user clicks the deletebox within the newly appended form, nothing happens. I.e. jquery doesn't register that it was clicked and no message is printed to the console. Do you know how this issue can be addressed?

Thanks!

Siavash
  • 2,599
  • 4
  • 26
  • 36
Jason Howard
  • 996
  • 7
  • 21
  • 4
    https://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements duplicated possible – Đào Minh Hạt Mar 17 '19 at 05:31
  • 4
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) and [In jQuery, how to attach events to dynamic html elements?](https://stackoverflow.com/questions/1359018) – adiga Mar 17 '19 at 06:27

2 Answers2

1

I needed to use

$(document).on('click', '.deletebox', function() {

rather than

 $(".deletebox").click(function () {
Jason Howard
  • 996
  • 7
  • 21
0

New button added after DOM loaded, so it is not registered in DOM and not getting click. Use below code for dynamic element click.

 $(document).on('click','.deletebox',function () {
        console.log('box was clicked')
    });