Cloning and renaming form elements with jQuery
- by Micor
I am looking for an effective way to either clone/rename or re-create address fields to offer ability to submit multiple addresses on the same page. So with form example like this:
<div id="addresses">
<div class="address">
<input type="text" name="address[0].street">
<input type="text" name="address[0].city">
<input type="text" name="address[0].zip">
<input type="text" name="address[0].state">
</div>
</div>
<a href="" id="add_address">Add address form</a>
From what I can understand there are two options to do that:
Recreate the form field by field and increment the index which is kind of verbose:
var index = $(".address").length;
$('<`input`>').attr({
name: 'address[' + index + '].street',
type: 'text'
}).appendTo(...);
$('<`input`>').attr({
name: 'address[' + index + '].city',
type: 'text'
}).appendTo(...);
$('<`input`>').attr({
name: 'address[' + index + '].zip',
type: 'text'
}).appendTo(...);
$('<`input`>').attr({
name: 'address[' + index + '].state',
type: 'text'
}).appendTo(...);
Clone Existing layer and replace the name in the clone:
$("div.address").clone().appendTo($("#addresses"));
Which one do you recommend using in terms of being more efficient and if its #2 can you please suggest how I would go about search and replacing all occurrences of [0] with [1] ([n]). Thank you.