I want to create two dynamic form elements so that when the user clicks "add another question" they get a new question field and a answer field and the html is manipulated to "Q2", "A2" etc. I was able to create a dynamic form element to add a new question input based on this blog but can't manage to add an answer field too.
//disable delete question
$(document).ready(function() {
$('#btnDel').prop('disabled', 'disabled');
});
//add question
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 2); // the numeric ID of the new Q input field being added
var newNumA = new Number(num + 3); // the numeric ID of the new A input field being added
// Question Input
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#qInput' + num).clone().prop('id', 'qInput' + newNum);
// manipulate the name/id/html of the span inside the new element
newElem.children(':first').prop('id', 'spanQ' + newNum).html("Q" + newNum);
// manipulate the name/id/val values of the input inside the new element
newElem.children().eq(1).prop('id', 'question' + newNum).prop('name', 'question' + newNum).val("");
//Answer Input
// create the new element via clone(), and manipulate it's ID using newNumA value
var newElemA = $('#aInput' + num).clone().prop('id', 'aInput' + newNumA);
// manipulate the name/id/html of the span inside the new element
newElemA.children(':first').prop('id', 'spanA' + newNumA).html("A" + newNumA);
// manipulate the name/id/val values of the input inside the new element
newElemA.children().eq(1).prop('id', 'answer' + newNumA).prop('name', 'answer' + newNumA).val("");
// insert the new element after the last "duplicatable" input field
$('#aInput' + num).after(newElem, newElemA);
// enable the "remove" button
$('#btnDel').prop('disabled', '');
// business rule: you can only add 19 questions
if (newNum == 19)
$('#btnAdd').prop('disabled', 'disabled');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="createWorksheet">
<div>
<div id="qInput1" class="styleOne clonedInput">
<span id="span1Q"> Q1 </span>
<input type="text" name="question1" id="question1" />
</div>
<div id="aInput2" class="styleTwo">
<span id="span1A"> A1 </span>
<input type="text" name="answer1" id="answer1" />
</div>
</div>
<div class="buttonGroup">
<input type="button" id="btnDel" value="Remove Question" class="btnCreate" />
<input type="button" id="btnAdd" value="Add another question" class="btnCreate" />
</div>
<div class="buttonGroup">
<input type="submit" id="btnSub" value="Submit" class="btnCreate">
</div>
</form>