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 = [
{ q: "What is 2+2?", a: ["3","4","5"], correct: "4" },
{ q: "Capital of France?", a: ["Berlin","Paris","Rome"], correct: "Paris" }
];
let index = 0, score = 0;
function loadQuestion() {
document.getElementById("question").innerText = questions[index].q;
let opts = "";
questions[index].a.forEach(option => {
opts += &lt;button onclick="checkAnswer('${option}')"&gt;${option}&lt;/button&gt;&lt;br&gt;
;
});
document.getElementById("options").innerHTML = opts;
}
function checkAnswer(ans) {
if (ans === questions[index].correct) score++;
document.getElementById("score").innerText = Score: ${score}
;
}
function nextQuestion() {
index++;
if (index < 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.
Leave a Reply