-1

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>
Tajmin
  • 353
  • 1
  • 7
  • 23
inaz
  • 1,755
  • 4
  • 20
  • 41
  • You question is confusing. You are appending a list to a div, so you cannot say "how can I remove the appended div" because you are not appending a div. Please, rewrite your question to be more clear. – Vicente Olivert Riera Aug 24 '16 at 10:59
  • Possible duplicate of [Jquery event handler not working on dynamic content](http://stackoverflow.com/questions/15090942/jquery-event-handler-not-working-on-dynamic-content) – yuriy636 Aug 24 '16 at 10:59

3 Answers3

2

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();
                });
            });

        })
Lalji Tadhani
  • 14,041
  • 3
  • 23
  • 40
  • Better would be to delegate event, this would avoid binding multiple click events to already previsously added element – A. Wolff Aug 24 '16 at 11:01
2

Change your script to:

$("body").on("click", ".remove", function () {
  $(this).closest("ul").remove();
});

You'll add a handler to each item with class '.remove', even when it's dynamically added. Also, I guess you want to remove the closest item 'ul'.

Working fiddle: https://jsfiddle.net/d9dehtqv/

Alan Jurczak
  • 479
  • 5
  • 14
1

Its okei? :)

https://jsfiddle.net/z51z3jj1/9/

<script>
    $("body").on('click', '.remove', function () {
        $(this).parents('.pricepart').remove();
    });
</script>
Daniel Díaz
  • 216
  • 4
  • 18