-
Notifications
You must be signed in to change notification settings - Fork 0
/
quize.js
95 lines (80 loc) · 2.73 KB
/
quize.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const quizData = [
{
question: "which of the following is the capital of arunachalpradesh",
options: ["itanagar", "dispur", "imphai", "panaji"],
answer: "itanagar"
},
{
question: "what is the national flower of india",
options: ["lotus", "hibiscus", "jasmin", "sunflower"],
answer: "lotus"
},
// Add more questions here
];
const questionElement = document.getElementById("question");
const optionsElement = document.getElementById("options");
const feedbackElement = document.getElementById("feedback");
const prevButton = document.getElementById("prev-btn");
const nextButton = document.getElementById("next-btn");
const submitButton = document.getElementById("submit-btn");
const resultContainer = document.getElementById("result");
let currentQuestion = 0;
let score = 0;
function loadQuestion() {
const currentQuizData = quizData[currentQuestion];
questionElement.innerText = currentQuizData.question;
optionsElement.innerHTML = "";
currentQuizData.options.forEach((option, index) => {
const optionElement = document.createElement("input");
optionElement.type = "radio";
optionElement.name = "option";
optionElement.value = option;
optionElement.id = "option" + index;
const labelElement = document.createElement("label");
labelElement.htmlFor = "option" + index;
labelElement.textContent = option;
optionsElement.appendChild(optionElement);
optionsElement.appendChild(labelElement);
});
}
function checkAnswer() {
const selectedOption = document.querySelector('input[name="option"]:checked');
if (selectedOption) {
const userAnswer = selectedOption.value;
const correctAnswer = quizData[currentQuestion].answer;
if (userAnswer === correctAnswer) {
feedbackElement.textContent = "Correct!";
score++;
} else {
feedbackElement.textContent = "Incorrect!";
}
selectedOption.checked = false;
} else {
feedbackElement.textContent = "Please select an option!";
}
}
function showResult() {
document.getElementById("quiz-container").style.display = "none";
resultContainer.innerHTML = <h2>Your Score: ${score}/${quizData.length}</h2>;
}
prevButton.addEventListener("click", () => {
currentQuestion--;
if (currentQuestion < 0) {
currentQuestion = 0;
}
loadQuestion();
});
nextButton.addEventListener("click", () => {
checkAnswer();
currentQuestion++;
if (currentQuestion >= quizData.length) {
showResult();
} else {
loadQuestion();
}
});
submitButton.addEventListener("click", () => {
checkAnswer();
showResult();
});
loadQuestion();