user2467599
user2467599

Reputation: 23

jQuery, dynamic form generation - emptying cloned input fields?

I'm creating a form with some input fields akin to:

<label>First Name<input type="text" id="firstname1" name="firstname1"></label>
<label>Last Name<input type="text" id="lastname1" name="lastname1"></label>

There's more to it but you get the gist. I've wrapped all the inputs into a container div and am using jQuery to clone that into an empty div. (So there's a button called 'replicate' for the user to click to create a new box of all the same input fields.)

$('#replicate').click(function(){
$('.container').clone().appendTo($('.emptyContainer'));

And then I need every new container to increment it's class by 1 every time a new container is created:

var container = $(".emptyContainer div").length;
var containerNumber = container + 1;
var containerClass = 'container' + containerNumber;
$(".emptyContainer .container").attr("class", containerClass);

It all seems to work as I want it to - the problem I'm facing now is that if there's any value in the first input fields the replicate button will create a new container that includes the info in the original fields. How might I overcome this?

Upvotes: 2

Views: 359

Answers (1)

Subedi Kishor
Subedi Kishor

Reputation: 5996

After you have cloned the container, you need to empty the input fields and then append to the target container.

$('#replicate').click(function(){
    var clonedElm = $('.container').clone();
    clonedElm.find('input').val('');
    cloneElm.appendTo($('.emptyContainer'));
});

Edit:

You said, you need every new container to increment it's class by 1 every time a new container is created. So in this case you need to remove the older class and assign a new class to the cloned container.

So this will be the solution:

$('#replicate').click(function(){
    var clonedElm = $('.container').clone();
    clonedElm.find('input').val('');
    var container = $(".emptyContainer div").length;
    var containerNumber = container + 1;
    var containerClass = 'container' + containerNumber;
    clonedElm.removeClass('container').addClass(containerClass);
    clonedElm.appendTo($('.emptyContainer'));
});

Check the demo fiddle.

Upvotes: 1

Related Questions