Cloning
You should be getting pretty comfortable manipulating elements in the DOM. You’ve learned how to add and remove elements, get measurement information, and set measurement information. Let’s turn our focus to duplicating elements on a page, a little thing jQuery calls cloning.
On the surface, cloning a group of elements on a page looks pretty simple. All you have to do is use the clone() function and you’re all set, right? Let’s dig a little further.
When you use the clone() method, you’re making a copy of the selected elements and all of their descendants and any text nodes contained within the selected items and the descendants. This is known as a deep copy.
You can also copy the entire set of event handlers bound to the selected elements, ensuring that your functions will continue to work even though you’re adding new elements to the DOM. You do this by setting the withDataAndEvents and deepWithDataAndEvents properties of clone() to true.
To demonstrate clone(), you’ll create a new form for the website that allows visitors to submit recipes. Some recipes have more ingredients than others, but you don’t want to clutter up the page with input elements. You’ll use the clone() method to allow form users to add as many ingredient fields as they need.
To use clone() to add form elements
- Use a fresh copy of the HTML5 boilerplate in your text editor and add the following markup to create a recipe form (Script 4.4.html):
<div id="content"> <h2>Submit a recipe...</h2> <form name="recipe" action="inc/php/recipe.php" method="post"> <input name="recipeName" placeholder="Recipe Name"/> <div id="ingredients"> <p>Ingredients</p> <span class="inputSpan"> <input name="recipeIngredient[]" placeholder="Ingredient" /> <br /></span> <span class="inputSpan"> <input name="recipeIngredient[]" placeholder="Ingredient" /><br /></span> <span class="inputSpan"> <input name="recipeIngredient[]" placeholder="Ingredient" /> <a href="newIngredient">add another ingredient</a> <br /></span> </div> <p>Instructions</p> <textarea name="recipeInstructions"> </textarea><br /> <input type="submit" name="submit" value="Submit Recipe" /> </form> </div>
Take note of the span tags surrounding the inputs for ingredients. These are used to make writing your code much easier and more compact. Additionally, each ingredient tag is named with square brackets ([]) to make them each part of an array that can be handled more easily by server-side languages like PHP.
- Save the file as recipe.html and upload it to your web server. When loaded into a browser, it looks like .
The new recipe form is almost ready to go.
- Add a function to jquery.custom.js to clone the last recipe ingredient span:
$('a[href="newIngredient"]') .click(function(e){ e.preventDefault(); var clonedInput = $('.inputSpan').filter(':last') .clone(true, true);
Using a class on the span tags surrounding it helps to keep your selector short. Be sure to set the clone() function’s properties to true, true so event handlers are copied.
- Get the current value of the last input. You’ll use this value to make sure you don’t lose any ingredients:
var lastInputData = $('input[name="recipeIngredient[]"]') .filter(':last').val();
- Set the last ingredient input’s HTML to get rid of the link and to ensure that it retains its current value:
$('.inputSpan').filter(':last') .html('<span class="inputSpan"><input name="recipeIngredient[]" placeholder="Ingredient" value="' + lastInputData + '" /><br /></span>');
Resetting the HTML of the element prevents it from creating the “add another ingredient” link again and again .
Duplicating the links not only looks bad, but also it’s confusing to the user.
- Append the cloned input to the ingredients div:
$('#ingredients') .append(clonedInput);
- Clean up the new input by setting its value to be blank and then placing the focus on the new input:
$('input[name="recipeIngredient[]"]') .filter(':last').val(''); $('input[name="recipeIngredient[]"]') .filter(':last').focus(); });
Setting the focus into the new input is a convenience for users. It allows them to just start typing when the new element is added.
- Save the jQuery file and upload it to your server. Reload recipe.html and click the “add another ingredient” link .
A new ingredient field has been added and now has the focus.
If you keep clicking the link, the click event handler is triggered each time without you having to resort to changing the event handler .
The click event is still triggered each time because you set up clone() to copy the event handlers for the form.