Reputation: 121
I have a simple form as follows so a user can type the name of a question:
<input type="text" id="question_name" name="question_name" value="">Question Name: <br />
<a href="#" id="addanother" onclick="addNewQuestion()">Add Another</a>
<div id="container"/>
<input id="go" name="btnSubmit" type="submit" value="Submit" class="btn" />
I am wanting to create a Javascript function (addNewQuestion()
) which allows a user to add another question dynamically by clicking the "Add Another" link. All the text boxes with the questions should be displayed on the screen.
I understand that it is using getElementById
and most likely a for
loop but I keep hitting a brick wall. Can anyone show me a simple solution please?
Upvotes: 0
Views: 51
Reputation: 10924
There are many ways to do this. Here's a simple example in plain JavaScript. Note that you will either want to avoid using id
s so they aren't duplicated in the DOM, or you will want to dynamically name them.
function addNewQuestion() {
var container = document.getElementById("questions");
var question = document.querySelector(".question");
container.appendChild(question.cloneNode(true));
return false;
}
.question { display: block }
<div id="questions">
<label class="question">
Question Name:
<input type="text" value="" />
</label>
</div>
<a href="#" id="addanother" onclick="return addNewQuestion()">Add Another</a>
Upvotes: 1