Search code examples
jqueryformscloneauto-increment

How to increment values on .clone() in jquery


I am trying to clone a form and change the form name from (for example) #form and when cloned to #form1 and do the same on the inputs and I am really stuck on how to do this! Any help would be GREATLY appreciated as I have spent ALL DAY trying to figure it out. Here is my code:

HTML:

<div class="avail">
<form action="submit.php" id="form1" method="post">
<input type="text" name="input1" />
<input type="text" name="anotherinput1" />
<input type="text" name="onemoreinput1" />
<input type="submit" name="submit1" value="submit" />
</form>
</div>

 <input type="submit" value="+" id="copy" />

JQUERY (for cloning the div and form):

$("#copy").click(function(e) {
       $(".avail").clone().removeAttr('id').insertBefore(this);
       e.preventDefault();
    });

Please if anyone knows how to do this, I would appreciate it soooo much!


Solution

  • You can just count how many avail objects you have and use that as the running count for the new form ID.

    $("#copy").click(function(e) {
       var avails = $(".avail");
       var cnt = avails.length + 1;
       avails.eq(0).clone().insertBefore(this).find("form").attr("id", "form" + cnt);
       e.preventDefault();
    });
    

    You can see it work here: http://jsfiddle.net/jfriend00/9CU85/

    If you also need to update the numbers on the name attributes of the input elements, then you can use this code to do that also:

    $("#copy").click(function(e) {
       var avails = $(".avail");
       var cnt = avails.length + 1;
       avails.eq(0).clone().insertBefore(this)
           .find("form").attr("id", "form" + cnt)
           .find("input").each(function() {
               this.name = this.name.replace(/\d+/, cnt);
           });
       e.preventDefault();
    });​
    

    You can see this one work here: http://jsfiddle.net/jfriend00/SKjMN/