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
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="quiz.css">
</head>
<body>
<div class="QuestionOne">
<form id="quizForm">
<h1> What is your favorite color?</h1>
<input type="radio" id="red" name="color" value="red">
<label for="red">Red</label><br>
<p></p>
<input type="radio" id="blue" name="color" value="blue">
<label for="blue">Blue</label><br>
<p></p>
<input type="radio" id="green" name="color" value="green">
<label for="green">Green</label>
<p></p>
<input type="submit" id="submit" name="color" value="Submit"><br>
</form>
</div>
<script src="quiz.js">
</script>
</body>
</html>
JavaScript
quizForm.addEventListener("submit",function(event) {
event.preventDefault();
var grabAnswer = document.getElementById('red')
console.log(grabAnswer.id);
if (grabAnswer.id == 'red') {
console.log('correct!');
}else{
console.log('wrong');
}
})
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
if (grabAnswer.id == 'red') {
to
if (grabAnswer.checked) {
(where grabAnswer is document.getElementById('red'))
quizForm.addEventListener("submit", function(event) {
event.preventDefault();
// get the correct answer
var grabAnswer = document.getElementById('red')
// see if it's been selected
if (grabAnswer.checked) {
console.log('correct!');
} else {
console.log('wrong');
}
})<div class="QuestionOne">
<form id="quizForm">
<h1> What is your favorite color?</h1>
<input type="radio" id="red" name="color" value="red">
<label for="red">Red</label><br>
<p></p>
<input type="radio" id="blue" name="color" value="blue">
<label for="blue">Blue</label><br>
<p></p>
<input type="radio" id="green" name="color" value="green">
<label for="green">Green</label>
<p></p>
<input type="submit" id="submit" name="color" value="Submit"><br>
</form>
</div>