Reputation: 2509
Here is a simple script I'm trying to run.
What I'm trying to do is add a new input box with every add button. I attached to every form, a delete button. When I click delete, the rows disappear as I want.
However when I delete all of them, I cannot add any more input fields. I assume this is because there's nothing to clone since all the list items have been deleted.
Should there be an if statement, saying if this is the remaining text, just empty the value like
$(this).parent('li').val("");
?
I don't know how to put that in..
Thank you
Upvotes: 1
Views: 57
Reputation: 30135
You could save one reference item in a variable and then clone from that. Also, IDs have to be unique so change the delete id to a class.
var item = $("#tasks ul li:eq(0)").clone(true, true); // need to clone for new add
$('#add').click(function() {
var taskItem = item.clone(true,true);
$('#tasks ul').append(taskItem);
taskItem.find(':input:text').val("");
return false;
});
$('body').on('click','.delete',function() {
$(this).parent('li').remove();
return false;
});
alternatively you could prevent deletion of the last item altogether:
if(!$(this).parent('li').is(':only-child')){
$(this).parent('li').remove();
}
Upvotes: 2