0

I am new to jquery and I am trying to make this code works but no way:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">Add</button>

<script>
    $(document).ready(function(){
        $("button.add").click(function() {
            $(this).after('<div><button class="remove">Remove</button></div>');
        });

        //Remove items from cart
        $("button.remove").click(function(){
            $(this).fadeOut();
        });

    });
</script>

When I try adding the following line <div><button class="remove">Remove</button></div> after the add button in the initial code, everything works properly. Anytime I add new remove buttons using the JS code, it works but i can not remove those buttons.

Kindly help me fix it.

Prince
  • 1,090
  • 3
  • 12
  • 23

2 Answers2

1

This is called event delegation.

You can see it as follows: jQuery loads the whole document object model into a variable or object on page startup. Everytime a jQuery function want to use an element it searches through that variable or object to find it. But with your code, the element is added after the variable or object is created and by that jQuery is not able to interact with it, because it doesn't know this element.

A simple solution:

$( "#parentDivOrElement" ).on( "click", "button.remove", function( event ) {
    $(this).fadeOut();
});

This basically let's jQuery find the element in the current DOM, after the update. You should replace #parentDivOrElement with the correct ID or class.

More about event delegation: https://learn.jquery.com/events/event-delegation/

Gerrit Luimstra
  • 512
  • 5
  • 22
0

Use:

$(body).on('click', 'button.remove', function(){
// do something
});
Ayan
  • 1,952
  • 2
  • 21
  • 58