(Adding and removing list items using JavaScript / jQuery

I am almost noob in JavaScript and jQuery (so I apologize if I did not find a suitable answer to my question in similar posts).

That's what. I have a list with a lot of materials in each element of the list:

<ul id="fruit_list">
    <li>
         <h4> Fruit 1: <a href="#" class="remove">remove</a> </h4>
         <p> blablabla </p>
    </li>

    <li>
         <h4> Fruit 2: <a href="#" class="remove">remove</a> </h4>
         <p> blablabla </p>
    </li>
</ul>

<a href="#" class="add">add</a>

What I want to do is when I click on the 'remove' binding to remove the list item containing it.

(If desired, I would like to manipulate the incremental number on Fruit 1, Fruit 2, etc. so that when I delete item # 2, the next becomes # 2, etc. But anyway.)

So here is what I wrote so far:

$(function(){
    var i = $('#fruit_list li').size() + 1;

    $('a.add').click(function() {
        $('<li><h4>Fruit '+i+':<a href="#" class="remove">
             remove</a></h4><p>Blabla</p></li>')
        .appendTo('#fruit_list');
        i++;
    });

    $('a.remove').click(function(){

        $(this).parentNode.parentNode.remove();
        /* The above obviously does not work.. */
        i--;
    });
});

An add anchor works as expected. "Remove" drinks lemonade ..

So, any ideas? thank

EDIT: ! ( ) , , :

$('a.remove').live('click', function(){
    $(this).closest('li').remove();
    i--;
});

!

+3
3

a.remove live http://api.jquery.com/live/. DOM doc.

, , parent() parentNode. jQuery, parentNode - DOM, remove(), it removeChild(). jQuery, parent().

+1

$(this).parents("LI").remove();

0

, $('a.remove') , . , ADD :

$('a.add').click(function() {
    var $li = $('<li><h4>Fruit '+i+':<a href="#" class="remove">
         remove</a></h4><p>Blabla</p></li>');
    $li.appendTo('#fruit_list');
    $li.find('a.remove').click(function() {
        $li.remove();
        i--;
    });
    i++;
});

.

EDIT: Oh, this will only work for the items you add, if you already load some list items in html before starting any Javascript, add this function to $('a.add').click:

$('a.remove').click(function(){
    $(this).parent().parent().remove();
    i--;
});
0
source

All Articles