-1

I have an unordered list with 2 li, I must add more li element with jquery also with a delete button, but now I need to remove this li with the button. The function works with the old li but not with the new created li...

       <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Prueba front</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
    </head>
    <body>
        <div id="text">
            <span>Car: </span>
            <input id="name" type="text"><button type="button" class="add">Add</button>
        </div>
        <div id="car-list">
            <ul>
                    <li>
                    Ford <button type="button">Remove</button>
                </li>
                <li>
                    Nissan <button type="button">Remove</button>
                </li>   
            </ul>
        </div>
        <script>
    $(function ()
    {
        $('.add').on('click', function(){   
            var car=$("#name").val(); 
            var li= $("<li> "+car +" <button type=button>Remove</button></li>");
            $("ul").append(li); 
        });

        $('button[class!="add"]').on('click', function(){
        $(this).parent().remove();   
        alert("it works!!");           
        });         
    });   
        </script>  
    </body>
    </html>

I need to remove the new li created with jquery.

How can I achieve this?

uedemir
  • 1,654
  • 1
  • 12
  • 21
Dany
  • 1
  • 1

1 Answers1

1

Replace your remove with this

$(document.body).on('click', 'button[class!="add"]',function(){
        $(this).parent().remove();   
        alert("it works!!");           
}); 

Your event must be tied to body and not to dynamic elements.

Merak Marey
  • 749
  • 5
  • 15
  • Thanks Merak, i didn´t know it, I thougt that an event could be tied to an element. It works!!! – Dany Feb 17 '19 at 12:19
  • Actually, it does. When you call your function the event gets attached to the elements that ALREADY exist, but if after that a new element is created, it will not get attached to the event. – Merak Marey Feb 17 '19 at 12:21
  • It doesn’t have to be body though, only the containing element. You’ll have better performance using the smallest possible container of the elements triggering the action on click. – Steve Chamaillard Feb 17 '19 at 12:43
  • Yes, but can you ensure that parent element would not get also removed/modified? Remember we are seeing here only portion of the code. The `body` is the slower but the most secure, otherwise as your app develops you must keep track of if the parent element also gets affected and update the code consequently. Besides, the SO must tag performance also as a factor to take into account. – Merak Marey Feb 17 '19 at 12:50