January 21st, 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:


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

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:

$('#butt').click(function(){
    
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
$(item).val($originalTextareas.eq(index).val());
});
$cloned.appendTo('#clonedItem');
});

Hope it helps.

  • SmileyGirl12

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

  • Aurelio Tapia

    Tanks budy, you save my day.