Quiz App (Intermediate–Advanced)

Why? Good for arrays, loops, event handling, and scoring.

<!DOCTYPE html>
<html>
<head>
  <title>Quiz App</title>
</head>
<body>
  <h2 id="question"></h2>
  <div id="options"></div>
  <button onclick="nextQuestion()">Next</button>
  <p id="score"></p>

  <script>
let questions = &#91;
  { q: "What is 2+2?", a: &#91;"3","4","5"], correct: "4" },
  { q: "Capital of France?", a: &#91;"Berlin","Paris","Rome"], correct: "Paris" }
];
let index = 0, score = 0;
function loadQuestion() {
  document.getElementById("question").innerText = questions&#91;index].q;
  let opts = "";
  questions&#91;index].a.forEach(option =&gt; {
    opts += &amp;lt;button onclick="checkAnswer('${option}')"&amp;gt;${option}&amp;lt;/button&amp;gt;&amp;lt;br&amp;gt;;
  });
  document.getElementById("options").innerHTML = opts;
}
function checkAnswer(ans) {
  if (ans === questions&#91;index].correct) score++;
  document.getElementById("score").innerText = Score: ${score};
}
function nextQuestion() {
  index++;
  if (index &lt; questions.length) loadQuestion();
  else document.getElementById("question").innerText = "Quiz Over!";
}
loadQuestion();
</script> </body> </html>

Explanation:

  • Questions stored in an array.
  • Loads one question at a time with options.
  • Checks correct answer and updates score.
  • Ends quiz when finished.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *