John Paul Manuel (JP)
4 months ago<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Quiz</title>
<style>
.container {
margin: 10px;
padding: 5px;
}
</style>
</head>
<body>
<div class="container">
<h4 id="number"></h4>
<h2 id="question"></h2>
<div id="choices"></div>
</div>
<button id="start" onclick="startGame()">Start Game</button>
<button id="next" onclick="nextQuestion()" disabled>Next</button>
<script>
const obj = {
results: [
{
question: "What is 1+1",
choices: ["11", "2", "4", "Undefined"],
correct_answer: "2",
},
{
question: "What is the english of aso",
choices: ["cat", "cow", "dog", "frog"],
correct_answer: "dog",
},
],
};
const questions = obj.results;
let currentIndex = 0;
const questionDisplay = document.getElementById("question");
const numberDisplay = document.getElementById("number");
const choicesDiv = document.getElementById("choices");
const startBtn = document.getElementById("start");
const nextBtn = document.getElementById("next");
function startGame() {
showQuestion();
startBtn.disabled = true;
}
function nextQuestion() {
currentIndex++;
nextBtn.disabled = true;
if (currentIndex >= questions.length) {
questionDisplay.textContent = "No questions left";
choicesDiv.innerHTML = "";
const restart = document.createElement("button");
restart.textContent = "Try Again";
restart.onclick = () => {
currentIndex = 0;
choicesDiv.innerHTML = "";
showQuestion();
};
choicesDiv.appendChild(restart);
} else {
showQuestion();
}
}
function showQuestion() {
numberDisplay.textContent = "Question " + (currentIndex + 1);
questionDisplay.textContent = questions[currentIndex].question;
let choices = questions[currentIndex].choices;
choicesDiv.innerHTML = "";
let answered = false;
choices.forEach((choice) => {
const button = document.createElement("button");
button.style.marginLeft = "10px";
button.style.padding = "10px";
button.textContent = choice;
button.onclick = () => {
if (answered) return;
answered = true;
if (choice == questions[currentIndex].correct_answer) {
button.style.backgroundColor = "green";
} else {
button.style.backgroundColor = "red";
}
nextBtn.disabled = false;
};
choicesDiv.appendChild(button);
});
}
</script>
</body>
</html>