-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path162. QuizApp.html
98 lines (85 loc) · 3.52 KB
/
162. QuizApp.html
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
96
97
98
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Quiz App</title>
</head>
<body style="background-color: black; color: azure">
<h1>Javascript Quiz App</h1>
<div id="quiz"></div>
<button id="submit">Submit</button>
<div id="results"></div>
<script>
const quizContainer = document.getElementById("quiz");
const submitButton = document.getElementById("submit");
const resultsContainer = document.getElementById("results");
const myQuestions = [
{
question: "What is the capital of France?",
answers: {
a: "Paris",
b: "London",
c: "New York",
},
correctAnswer: "a",
},
{
question: "What is the largest country in the world?",
answers: {
a: "Russia",
b: "China",
c: "United States",
},
correctAnswer: "a",
},
{
question: "What is the currency of Japan?",
answers: {
a: "Yuan",
b: "Euro",
c: "Yen",
},
correctAnswer: "c",
},
];
(function buildQuiz() {
const output = [];
myQuestions.forEach((currentQuestion, questionNumber) => {
const answers = [];
for (letter in currentQuestion.answers) {
answers.push(
`<label><input type="radio" name="question${questionNumber}" value="${letter}" />${letter} :${currentQuestion.answers[letter]}</label>`
);
}
output.push(
`<div class="question">${currentQuestion.question}</div>
<div class="answers">${answers.join("")}</div>`
);
});
quizContainer.innerHTML = output.join("");
})();
submitButton.addEventListener("click", function showResults() {
const answerContainers =
quizContainer.querySelectorAll(".answers");
let numCorrect = 0;
myQuestions.forEach((currentQuestion, questionNumber) => {
//find selected answer
const answerContainer = answerContainers[questionNumber];
const selector = `input[name=question${questionNumber}]:checked`;
const userAnswer = (
answerContainer.querySelector(selector) || {}
).value;
if (userAnswer === currentQuestion.correctAnswer) {
numCorrect++;
answerContainers[questionNumber].style.color = "green";
} else {
answerContainers[questionNumber].style.color = "red";
}
});
resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;
});
</script>
</body>
</html>