0

I have a form with a button that is able to dynamically add a div that contains a paragraph and a "remove" button:

<!--form-->
<form></form>

<!--dynamically add div with paragraph and remove button-->
<button onclick="addParagraph()">Add Paragraph</button>

<script>

    //remove div
    $(".remove").click(function() {
        $(this).parent.remove();
    });

    //add paragraph div
    function addParagraph(){
                $("form").append('<div><textarea></textarea><button class="remove">Remove</button></div>');
    }

</script>

Unfortunately, if I add more than one div and click a remove button, it removes all of the dynamically generated divs. How can I get it so it just removes the one div?

I have also tried $(this).closest("div").remove();, but same result.

rpivovar
  • 3,150
  • 13
  • 41
  • 79

2 Answers2

2

Perform event delegation for dynamically added elements.

$(document).on('click',".remove",function() {
     $(this).parent.remove();
});

Working Snippet below:

//remove div
$(document).on('click', ".remove", function(e) {
  $(this).parent().remove();
});

//add paragraph div
function addParagraph() {
  $("form").append('<div><textarea></textarea><button class="remove">Remove</button></div>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form></form>
<button onclick="addParagraph()">Add Paragraph</button>
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
1

For dynamically created element you have to use .live() However, live() was deprecated in 1.7 in favour of on(), and completely removed in 1.9. The live() signature:

If you have greater version of jQuery than 1.9 you can use jQuery.fn.on

I would recommend to use .on below is a signature of .on function

$(document).on( eventName, selector, function(){} );

$("body").on("click", ".remove", function(event){
    //Do Some stuff
});

Solved version:

$("body").on('click', '.remove', function(event)
{
     $(this).parent.remove();
});
Curiousdev
  • 5,668
  • 3
  • 24
  • 38