0

When I click on the button "remove" of the new elements added does not happen any action. But when I click on that has already been loaded in the html it is removed. Could someone explain and help me?

    <div id="ubber">
    <div class="box">
        <p>Box </p>
        <button class="btn btn-danger remove-button">Remove</button>
    </div> <!-- box -->
</div> <!-- ubber -->

<button class="btn btn-success" id="addnew">add new box</button>

<script src="jquery.min.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){

    //add
        $('#addnew').on('click', function(){
            $('#ubber').append('<div class="box"><p>Box <span id="sum">0</span></p><button class="btn btn-danger remove-button">Remove</button></div> <!-- box -->');
        }); 

    //remove
        $('.remove-button').on('click' ,function(){
            $(this).closest('div').remove();
        })

    });
</script>
onlymax
  • 7
  • 1
  • You need to use event delegation. See the answers here [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) `$('#ubber').on('click','.remove-button',function(){});` – Shaunak D May 16 '15 at 05:05
  • I think this is wrongly marked as a duplicate, he is not asking about event delegation. He is incorrectly navigating in jQuery and thinks he is removing divs that way – AmmarCSE May 16 '15 at 05:09
  • @AmmarCSE What do you mean by *incorrectly navigating*? || OP: *When I click on the button "remove" of the new elements added does not happen any action.* - this says its is related to event binding on new elements. – Shaunak D May 16 '15 at 05:19
  • @ShaunakD, no, he dynamically adds boxes and tries removing them by using $(this).closest('div').remove(); although what he is trying to remove are siblings and not parent – AmmarCSE May 16 '15 at 05:21
  • *NO*, the button has only one sibling `

    `, removing it will be irrelevant. He wants to remove parent `.box` which `.closest('div')` would achieve. Anyways, if OP thinks the duplicate is wrong, he can always comment and we can reopen.

    – Shaunak D May 16 '15 at 05:24

1 Answers1

0

Use Event Delegation for this:

 $(document).on('click' , '.remove-button', function(){
     $(this).closest('div').remove();
 });

FIDDLE

Brijesh Bhatt
  • 3,810
  • 3
  • 18
  • 34