inaz inaz - 3 months ago 9
Javascript Question

remove the appended div each time that i click on REMOVE

i have a list that i append new div when i click in "Add".how can i remove the appended div each time that i click on REMOVE.
here is my code:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="content">
<ul class="pricepart">
<li><input type="text" />
<span class="add">ADD+</span></li>
</ul>
</div>
<div class="content">
<ul class="pricepart">
<li> <input type="text" />
<span class="add">ADD+</span></li>
</ul>
</div>
<script>
$(".add").click(function () {
$(this).closest('.content').append('<ul class="pricepart"><li><input type="text"/><span class="remove">Remove -</span></li></ul>');
});
</script>

<script>
$(".remove").click(function () {
$(this).closest('.content').remove();
});
</script>

</body>
</html>

Answer

try this way

$(document).ready(function () {
            $(".add").click(function () {
                $(this).closest('.content').append('<ul class="pricepart"><li><input type="text"/><span class="remove">Remove -</span></li></ul>');

                $(".remove").click(function () {
                    $(this).parents('ul').remove();
                });
            });

        })
Comments