simbada simbada - 6 months ago 16
Javascript Question

Add HTML form on button click

I have an HTML form in my website/application.

The form has lots of fields of input text, select, and PHP code, as well, to fill drop down values.

Is there any way I can clone/create the same form when the user clicks on the Add button? Let's say, if the user clicks 5 times, it would have five forms on the UI.

HTML

<form id = "buyerForm" role="form" method="POST" enctype="multipart/form-data" style="margin-top:30px;">
<span class="customerno" style="font-size: 22px;">Buyer 1 (Form 2)</span>

<div class="form-group">
<label>APPLICANT DETAILS</label>
</div>

<div class="form-group">
<label>Mr. / Mrs</label>
<select class="form-control" name="jnameTitle" id="jnameTitle">
<option>Please Select One</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="MS">MS</option>
</select>
</div>


// similar fields are omitted to reduce the complexity


<div class="form-group">
<label>Address</label>
<textarea name="jaddress" id="jaddress" class="form-control" cols="80" rows="5" ></textarea>
</div>

<button type="submit" name="jointCustomers" id="jointCustomers" class="btn btn-success btn-lg btn-flat">Save</button>
<button type="reset" class="btn btn-default btn-lg">Reset</button>

</form>

Answer

if you're using jQuery (or dont mind using it) you could just use clone to add the form again to the parent container

$("#youButton").click(function(){   
    $("#buyerForm").clone().appendTo("#yourParentWrapper");  
});

see this fiddle

Comments