Jan 21, 2011

Clone html form elements with selected options using jQuery

The object is to clone filled html form and append to another place with selected options. Consider following code:

<div id="container">
<input type="text" value="" /><br />
<textarea></textarea><br />
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select> <br/>
<input type="checkbox" name="chk" />Checkbox1<br />
<input type="checkbox" name="chk" /> Checkbox2 <br />
<input id="butt" type="button" value="Test" />
<div id="clonedItem"></div>

In above code, we have to copy container div and paste in clonedItem with selected options on button click.
See following code

$('#butt').click(function(){ $('form #container').clone(true).appendTo('#clonedItem');

There are problems in dropdownlist and text area. The selected option is not applied in clonedItem and textarea’s value are also not cloned. I am testing on firefox 3.6 using jquery 1.4.3. See following code to do it:

var $orginal = $('form #container');
var $cloned = $orginal.clone();

//get original selects into a jq object
var $originalSelects = $orginal.find('select');
$cloned.find('select').each(function(index, item) {
     //set new select to value of old select
     $(item).val( $originalSelects.eq(index).val() );

//get original textareas into a jq object
var $originalTextareas = $orginal.find('textarea');

$cloned.find('textarea').each(function(index, item) {
//set new textareas to value of old textareas

Hope it helps.


  1. How can I take the values from the textarea and checkboxes and add them to one individual textarea??

Leave a Reply

Your email address will not be published. Required fields are marked *