Skip to content

Instantly share code, notes, and snippets.

@qutek
Created June 11, 2014 10:25
Show Gist options
  • Save qutek/8e145acec72c821c0099 to your computer and use it in GitHub Desktop.
Save qutek/8e145acec72c821c0099 to your computer and use it in GitHub Desktop.
Jquery Clone Form
<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>
<script>
$('#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');
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment