0

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?

3
  • Are you open to jQuery? Commented Feb 17, 2016 at 16:24
  • @dave I can actually do this using an array in jquery just fine, but i'm required to use just javascript. Commented Feb 17, 2016 at 16:26
  • Don't use onclick. Commented Feb 17, 2016 at 23:46

1 Answer 1

1

There are many ways to do this. Here's a simple example in plain JavaScript. Note that you will either want to avoid using ids 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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.