CLONE
by LyndseyB
HTML
<form>
<!-- SET THIS AS A HIDDEN FIELD. ON PHP PAGE, USE THIS NUMBER AS LOOP IDENTIFIER-->
<input type="text" name="iterations" id="iterations" value="1" />
<fieldset>
<div class="myForm">
<span> Input 1 </span>
<input id="input1" name="input1" value="I am input 1" />
</div>
<input type="button" id="add_input" value=" Add Another! "/>
</fieldset>
</form>
CSS
div { display:inline; }
JavaScript
var i=1;
$(function() {
var cloneInput = function() {
i++;
//clone existing input
var newInput = $('div.myForm').clone()
//remove class so the appended div doesn't get the same class
.removeClass("myForm")
//find both the span and the input
.find(":input, span")
//set new name and id of input
.attr({
id: "input"+i,
name:"input"+i,
value:"I am input" +i
})
//set html of the span
.html("<br /> Input " +i+ " ")
//append the clone to the page
.appendTo("fieldset");
//set number of iterations in hidden field
$("#iterations").val(i);
};
$('#add_input').click(cloneInput);
});