I'm trying to dynamically add and remove items when I press the Append/Clear buttons in this piece of code.
$("#btn1").click(function(){
$("ul").prepend("<li>List Item</li>");
});
$("#btn2").click(function(){
$("ul").remove();
});
$("#btn3").click(function(){
$("p").prepend("Prepended items");
});
$("#btn4").click(function(){
$("p").remove();
});
How do I make it so that when I press btn1 multiple times it will add a number after it like:
List Item 1
List Item 2
List Item 3
Then if I press btn2 it will remove them one by one? same goes for btn4?
EDIT:
I used Jai and Oday's answers to suit my needs.
var i = 1, p = 1;
$("#btn1").click(function(){
$('<li/>',{
text: "List Item "+i
}).appendTo('ul');
i++;
});
$("#btn2").click(function(){
$("ul li:last").fadeOut('fast').remove();
i--; //added this
});
$("#btn3").click(function(){
$("p").append("<span>Appended items</span>");
});
$("#btn4").click(function(){
$("p").find('span:last').remove();
});
Try with something like this:
var i = 1, p = 1;
$("#btn1").click(function(){
$('<li/>',{
text: "List Item "+i
}).appendTo('ul');
i++;
});
$("#btn2").click(function(){
$("ul li:last").fadeOut('fast').remove();
});
$("#btn3").click(function(){
$('<p/>',{
text: "Prepended items "+p
}).appendTo('ul');
p++;
});
$("#btn4").click(function(){
$("p").fadeOut('fast').remove();
});
$("#btn1").click(function(){
$("ul").append("<li>List Item</li>");
});
$("#btn2").click(function(){
$("ul").find('li:last').remove();
});
$("#btn3").click(function(){
$("p").append("<span>Appended items</span>");
});
$("#btn4").click(function(){
$("p").find('span:last').remove();
});
Read more about jQuery functions: append, prepend, remove, empty, find,etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With