jQuery - dynamically append and remove ordered items

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
MarPlo
Posts: 186

jQuery - dynamically append and remove ordered items

I'm trying to dynamically add and remove items with jQuery when I press the Append /Remove buttons.
This is the html code:

Code: Select all

<ul id="lists">
  <li>List Item 0</li>
</ul>
<button id="btn1">Append List</button>
<button id="btn2">Remove List</button>
How do I make it so that when I press #btn1 multiple times it will add each time a <li> element with an ordered number after it? Like this:

Code: Select all

List Item 1
List Item 2
List Item 3
Then if I press #btn2 it will remove the last item?

Admin Posts: 805
Use the append() and remove() jquery methods, like in this example:

Code: Select all

<ul id="lists">
  <li>List Item 0</li>
</ul>
<button id="btn1">Append List</button>
<button id="btn2">Remove List</button>
<script>
var it = 1;

// append LI in #lists
$('#btn1').click(function(){
  $('#lists').append('<li>List Item '+ it +'</li>');
  it++;
});

// Remove last LI from #lists
$('#btn2').click(function(){
  $('#lists li:last').remove();
  it--;
});
</script>