Matt
Matt

Reputation: 2509

How do I clone a row when all of them are deleted in jQuery?

Here is a simple script I'm trying to run.

http://jsfiddle.net/T8q5p/5/

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

Answers (1)

Andy
Andy

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.

http://jsfiddle.net/T8q5p/6/

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

Related Questions