Web Development Kodex

multiple choice quiz

custom.js

'use strict'
const firstQuestion = document.getElementById('first-question')
const answers = firstQuestion.querySelectorAll('input')
const submit = document.getElementById('submit')
const result = document.getElementById('result')
for (let i = 0; i < answers.length; i++) {
answers[i].addEventListener('click', selectAnswer)
}
function selectAnswer () {
// Reset checkboxes to unchecked
for (let i = 0; i < answers.length; i++) {
answers[i].checked = false
}
this.checked = true
}
submit.addEventListener('click', checkAnswer)
function checkAnswer () {
for (let i = 0; i < answers.length; i++) {
if (answers[i].id === 'b') {
if (answers[i].checked === true) {
result.innerHTML = 'Correct!'
} else {
result.innerHTML = 'Wrong!'
}
}
}
}

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Multiple Choice Quiz</title>
<meta name="robots" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Site Name</h1>
</header>
<div class="wrapper">
<div class="container">
<p>Which artist uses pollen collected from flowers to create art?</p>
<div id="first-question">
<label for="a">Richard Long</label>
<input id="a" name="a" type="checkbox">
<label for="b">Wolfgang Laib</label>
<input id="b" name="b" type="checkbox">
<label for="c">Andy Goldsworthy</label>
<input id="c" name="c" type="checkbox">
</div>
<p id="result"></p>
<button id="submit">Submit</button>
</div>
<!-- .container-->
</div>
<!-- .wrapper-->
<footer>
<small><a href="https://opensource.org/licenses/MIT">MIT</a></small>
</footer>
<script src="custom.js"></script>
</body>
</html>

styles.css

body {
background: #eeeeee;
font-size: 16px;
font-family: "Trebuchet MS", Helvetica, sans-serif;
margin: 0;
}
a {
color: crimson;
text-decoration: none;
}
a:hover {
color: red;
}
/* Layout
------------------------------------------*/
header,
.container,
footer {
margin: 0 auto;
width: 88%;
max-width: 1080px;
}
.wrapper {
padding: 1em 0;
background: #ffffff;
}