NightHawk
NightHawk

Reputation: 3681

Cloning with jQuery

I have a form that allows users to refer friends. I want to add a link below the two input fields, "friend email" and "friend name", that will clone "friend-box" one time and add it below. In addition, the name attribute of "friend email" and "friend name" are name="friend_email[0]" and name="friend_name[0]" as suggested here. What's the best way to clone and increment the subscript? Here's the code:

<div class="friend-box">

    <div class="field">
        <span><label for='friend_name'><strong>Friend's Name *</strong></label> </span>
        <input id='friend_name' name='friend_name[0]' type='text' />
    </div>

    <div class="field">
        <span><label for='friend_email'><strong>Friend's Email *</strong></label></span>
        <input id='friend_email' name='friend_email[0]' type='text' />
    </div>

</div>

What's the best way to do this? One of the problems I had for example, is that when I cloned "friend-box" once and then twice, it obviously cloned it exponentially. So I'm guessing I need to have an ID number in there as well and increment it. Or, which is another method I saw, is to clone the "friend-box" when the page loads and keep cloning it from memory.

Thanks, Ryan

Upvotes: 3

Views: 1500

Answers (2)

superUntitled
superUntitled

Reputation: 22527

I have created an example here: http://jsfiddle.net/K8hhW/5/

You do not need to worry about incrementing the numbers in the brackets, the form does this automatically for you.

Upvotes: 1

Christian Joudrey
Christian Joudrey

Reputation: 3461

You don't need to specify the index [0], as long as you put [] the browser will automatically increment the index.

As for your question, here's how I would do it: http://jsfiddle.net/EJv4g/3/

Basically, I added a div.friend-boxes which wraps all friend boxes. I use jQuery to obtain the first friend box, clone it then reset the input field values (in case they were filled). I then append it to the .friend-boxes element.

You can change the append to prepend if you want it to be prepended.

Hope this helps!

  • Christian

Upvotes: 1

Related Questions