I am almost a noob at JavaScript and jQuery, (so I apologize if I didn't recognize a suiting answer to my question, in similar posts).
Here is the thing. I have a list with lots of stuff in each list item:
<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 anchor 'remove', to remove the list item containing it.
(Optionally I would like to manipulate the incremental number at Fruit 1, Fruit 2 etc, in a way that when I remove item #2, then the next one becomes the #2 etc. But anyway.)
So here is what I've written 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--;
});
});
The 'add' anchor works as expected. The 'remove' drinks a lemonade..
So, any ideas? Thanks
EDIT: Thanks for your answers everybody! I took many of your opinions into account (so I won't be commenting on each answer separately) and finally got it working like this:
$('a.remove').live('click', function(){
$(this).closest('li').remove();
i--;
});
Thank you for your rapid help!
$('a.remove').click(function(){=>$('a.remove').live('click',function(){