Cloning and renaming form elements with jQuery

Posted by Micor on Stack Overflow See other posts from Stack Overflow or by Micor
Published on 2010-04-16T00:05:38Z Indexed on 2010/04/16 0:23 UTC
Read the original article Hit count: 568

Filed under:

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:

  1. 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(...);
    
  2. 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.

© Stack Overflow or respective owner

Related posts about jQuery