Ricky Ahn
Ricky Ahn

Reputation: 191

jQuery appending remove button to list keeps adding an extra button

I have a list which i want users to be able to add another one by clicking a button. When the list gets added a remove button should appear.

Whenever I keep adding a new item there is an extra close button being appended resulting in something like this

.
..
...
....
.....
......

here is my js

 $('a').on('click', function(e){
   e.preventDefault();
   var a = $(this).closest('form').find('ol, li').last().html();
   console.log(a);
    var closeButton = "<a href='#' class='remove-upgrade-field'>Remove</a>" 
    $('<li>' + a + closeButton + '</li>' ).appendTo('ol');

 });

 $('.remove-upgrade-field').live('click', function(e){
   e.preventDefault();
   $(this).closest('li').remove();
 });

fiddle

Upvotes: 2

Views: 148

Answers (2)

Alex Char
Alex Char

Reputation: 33228

Change to this:

js

$('a').on('click', function(e){
    e.preventDefault();
    var a = $(this).closest('form').find('ol, li').last().children().html()
    console.log(a);
    var closeButton;
    closeButton = "<a href='#' class='remove-upgrade-field'>Remove</a>" 
    $('<li>' + a + closeButton + '</li>' ).appendTo('ol');

});

$('.remove-upgrade-field').live('click', function(e){
    e.preventDefault();
    $(this).closest('li').remove();
});

fiddle

Upvotes: 2

Augustus Francis
Augustus Francis

Reputation: 2670

It is becuase var closebutton is append each time you click it with

"<a href='#' class='remove-upgrade-field'>Remove</a>" 
    $('<li>' + a + closeButton + '</li>' ).appendTo('ol');

Try logging the o/p of closebutton in the console.

Upvotes: 0

Related Questions