I am learning DOM and wanted to create a simple JavaScript with Html quiz (for exercise). Now the problem I’m having is that when I hit submit, all of the answers are right instead of one being right and 3 being wrong. I think it is a problem with my html and the way I assigned the ID’s to the different tags but I cannot figure out what I am doing wrong.
Code
HTML
JavaScript
x
37
37
1
<html lang="en" dir="ltr">
2
<head>
3
<meta charset="utf-8">
4
<title></title>
5
<link rel="stylesheet" href="quiz.css">
6
7
</head>
8
9
<body>
10
11
<div class="QuestionOne">
12
<form id="quizForm">
13
<h1> What is your favorite color?</h1>
14
15
<input type="radio" id="red" name="color" value="red">
16
<label for="red">Red</label><br>
17
<p></p>
18
<input type="radio" id="blue" name="color" value="blue">
19
<label for="blue">Blue</label><br>
20
<p></p>
21
<input type="radio" id="green" name="color" value="green">
22
<label for="green">Green</label>
23
<p></p>
24
<input type="submit" id="submit" name="color" value="Submit"><br>
25
</form>
26
</div>
27
28
29
30
31
32
<script src="quiz.js">
33
34
</script>
35
</body>
36
</html>
37
JavaScript
JavaScript
1
15
15
1
quizForm.addEventListener("submit",function(event) {
2
event.preventDefault();
3
var grabAnswer = document.getElementById('red')
4
console.log(grabAnswer.id);
5
6
7
if (grabAnswer.id == 'red') {
8
console.log('correct!');
9
}else{
10
console.log('wrong');
11
}
12
13
14
})
15
Thanks.
Advertisement
Answer
You can do this two ways
- get the selected value and see if it’s correct
- get the correct answer and see if it’s selected
The existing answer handles (1) so here’s the solution for the other option.
Taking your original code, change
JavaScript
1
2
1
if (grabAnswer.id == 'red') {
2
to
JavaScript
1
2
1
if (grabAnswer.checked) {
2
(where grabAnswer
is document.getElementById('red')
)
JavaScript
1
13
13
1
quizForm.addEventListener("submit", function(event) {
2
event.preventDefault();
3
4
// get the correct answer
5
var grabAnswer = document.getElementById('red')
6
7
// see if it's been selected
8
if (grabAnswer.checked) {
9
console.log('correct!');
10
} else {
11
console.log('wrong');
12
}
13
})
JavaScript
1
16
16
1
<div class="QuestionOne">
2
<form id="quizForm">
3
<h1> What is your favorite color?</h1>
4
5
<input type="radio" id="red" name="color" value="red">
6
<label for="red">Red</label><br>
7
<p></p>
8
<input type="radio" id="blue" name="color" value="blue">
9
<label for="blue">Blue</label><br>
10
<p></p>
11
<input type="radio" id="green" name="color" value="green">
12
<label for="green">Green</label>
13
<p></p>
14
<input type="submit" id="submit" name="color" value="Submit"><br>
15
</form>
16
</div>