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 pro开发者_如何学Cblems 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
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.
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
精彩评论