Page 1 of 1

jQuery - dynamically append and remove ordered items

Posted: 10 Jan 2015, 15:40
by MarPlo
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?

jQuery - dynamically append and remove ordered items

Posted: 10 Jan 2015, 15:48
by Admin
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>