-1

If I was going to make a quiz, in which all of the questions needed to have the same format, and the user has to only be shown 1 question at a time, how would I do this without copying and pasting the code? Could I make a template? That would be my prefered option.


Thank you in advance.
Benjamin Sommer
  • 1,058
  • 3
  • 15
  • 35

1 Answers1

1

If you just want to show one question at a time, you could get the question's text element and the choices with JavaScript and change them by the following question.

You can also generate a template via JavaScript or another HTML file that gets copied whenever is needed with document.write() or innerHTML.

A small example of how it could be done:

var questions = ["2 + 2", "1 + 3", "8 / 2", "5 - 2"];
var currentQuestion = 0;
var answers = [];

function nextQuestion() {
  //Store answers:
  var value = $("input[name=options]:checked").val();
  answers.push(value);
  console.log(answers);


  //Next question:
  currentQuestion++;
  document.getElementById("question").innerHTML = questions[currentQuestion];

}
/* Apply your styles*/

#question {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="question">2 + 2?</div>
<form action="">
  <input type="radio" name="options" value="5">5<br>
  <input type="radio" name="options" value="4">4<br>
  <input type="radio" name="options" value="3">3
</form>

<button onclick="nextQuestion()">next question</button>

https://jsfiddle.net/z0n4xekh/23/