The code isn’t doing what I would like it to. I’m sure something is missing but don’t know what. When I click the “check score” button I would like it to show the score but for now, it only shows "You scored: 0/10. My displayScore() function doesn’t work. Could anyone tell me what I’m missing here? Observe that there is two possible correct answers for the questions with checkboxes.
JavaScript :
(function () {
function renderQuiz() {
const quizContainer = document.querySelector("#quizContainer");
let quizStr = '';
// Loops over the object properties (obj) and also takes an index parameter
quiz.forEach((obj, questionIndex) => {
// Empty string to keep the li element containing the label and input
let answerStr = '';
//Loops over the options object inside of the array quiz
for (const option in obj.options) {
/* If it has an object that has an array as a value it renders the inputs as checkboxes */
if (Array.isArray(obj.correct) === true) {
answerStr += `
<li>
<label>
<input
value=""
type="checkbox"
name="question-${questionIndex}"
data-correct="${obj.correct}"
>
${obj.options[option]}
</label>
<li> `;
/* Else it renders the inputs as radiobuttons */
} else {
answerStr += `
<li>
<label>
<input
type="radio"
name="question-${questionIndex}"
data-correct="${obj.correct}"
>
${obj.options[option]}
</label>
<li> `;
}
}
quizStr += `
<form>
<h3>${obj.question}</h3>
<ul>
${answerStr}
</ul>
</form> `;
})
quizContainer.innerHTML = quizStr;
}
const resultsContainer = document.querySelector("#results");
// Adds held score to total and displays a text with the score
function displayScore() {
const answerContainer = [];
quiz.forEach((obj, questionIndex) => {
let userAnswer = `input[name="question-${questionIndex}]:checked`;
let answers = [];
if (userAnswer >= 2) {
userAnswer.forEach(e => {
let selected = e.target.userAnswer;
answers.push(selected);
})
} else {
answers = userAnswer[0];
}
answerContainer.push(answers);
});
let score = 0;
for (let i = 0; i < quiz.length; i++) {
let correctAnswer = quiz[i].correct;
let userChoice = answerContainer[0];
if (Array.isArray(correctAnswer)) {
if (JSON.stringify(correctAnswer) === JSON.stringify(userChoice)) {
score++;
}
} else if (correctAnswer === userChoice) {
score++;
}
}
resultsContainer.innerHTML = `<p>You scored : ${score} / ${quiz.length}</p>`;
}
// Objects with question sections within an array
let quiz = [
{
question: "I vilket land produceras det mest kaffe?",
options: {
a: "Kolombia",
b: "Brasilien",
c: "Indonesien",
d: "Vietnam"
},
correct: "b"
},
{
question: "I vilket land konsumeras det mest kaffe?",
options: {
a: "Italien",
b: "Belgien",
c: "Finland",
d: "Kanada"
},
correct: "c"
},
{
question: "Ordet kaffe betyder vin på det språket det härstammar ifrån. Vilket språk är det?",
options: {
a: "Arabiska",
b: "Ryska",
c: "Turkiska",
d: "Grekiska"
},
correct: "a"
},
{
question: "Hur många kalorier finns i en kopp kaffe?",
options: {
a: "1",
b: "5",
c: "14",
d: "7"
},
correct: "a"
},
{
question: "Vem upptäckte kaffet?",
options: {
a: "En bonde",
b: "En fåraherde",
c: "En munk",
d: "En jägare"
},
correct: "b"
},
{
question: "På vilket djurs avföring är världens dyraste kaffe gjord på?",
options: {
a: "Mus",
b: "Fågel",
c: "Apa",
d: "Katt"
},
correct: "d"
},
{
question: "När kom kaffet till Sverige?",
options: {
a: "1700-talet",
b: "1800-talet",
c: "1400-talet",
d: "1600-talet"
},
correct: "d"
},
{
question: "Vilka två av dessa alternativ är typer av kaffe?",
options: {
a: "Arabica",
b: "Mocca",
c: "Robusta",
d: "Java"
},
correct: ["a", "c"]
},
{
question: "Välj de enda två delstaterna i U.S.A som odlar kaffebönor?",
options: {
a: "Georgia",
b: "Kalifornien",
c: "Hawaii",
d: "Florida"
},
correct: ["b", "c"]
},
{
question: "Hur förvaras kaffe som bäst? Välj två sätt.",
options: {
a: "Svalt",
b: "I kylskåp",
c: "Öppet",
d: "Mörkt"
},
correct: ["a", "d"]
}
];
renderQuiz();
let checkButton = document.querySelector("#check");
checkButton.addEventListener("click", displayScore)
})();
HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.0/css/all.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Montserrat&family=Poppins&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<title>Kaffe Quiz</title>
</head>
<body>
<main>
<div id="toggleBtns">
<button id="black" class="btn active">Black</button>
<button id="milk" class="btn">Milk</button>
</div>
<section id="quizSection">
<h1><i class="fas fa-mug-hot"></i>Kaffe Quiz<i class="far fa-lightbulb"></i></h1>
<div id="quizContainer"></div>
<div id="buttonContainer">
<button id="retry">TRY AGAIN</button>
<button id="check">CHECK SCORE</button>
</div>
<div id="results"></div>
</section>
</main>
<script src="script.js"></script>
</body>
</html>
CSS :
* {
box-sizing: border-box;
}
body {
font-family: 'Poppins', sans-serif;
color: white;
}
main::before {
content: '';
background-image:linear-gradient(
115deg,
rgba(236, 225, 203, 0.5),
rgba(228, 203, 163, 0.5)
), url(https://images.pexels.com/photos/1695052/pexels-photo-1695052.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500)
;
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
z-index: -1;
background-position: center;
filter: grayscale(45%);
}
#toggleBtns {
display: flex;
justify-content: center;
align-self: center;
text-align: center;
margin-top: 70px;
}
#toggleBtns button {
width: 60px;
font-weight: bolder;
height: 40px;
cursor: pointer;
}
.active, .btn button:hover {
border: 2px solid turquoise;
}
#black {
background: rgba(37, 37, 36);
color: white;
}
h1{
text-align: center;
letter-spacing: 3px;
font-size: 30px;
}
i {
margin: 20px;
}
#quizSection {
max-width: 800px;
min-width: 450px;
background: rgba(37, 37, 36, 0.9);
border-radius: 20px;
overflow: hidden;
margin: 50px auto;
}
h3 {
margin: 50px auto;
border-bottom: 1px solid rgba(116, 116, 110, 0.9);
max-width: 700px;
padding: 30px;
letter-spacing: 2px;
font-weight: bolder;
}
p {
font-size: 30px;
margin: 100px auto;
text-align: center;
}
input {
margin-left: 50px;
margin-right: 30px;
}
label {
margin-left: 20px;
font-size: 18px;
}
ul {
list-style: none;
}
li {
line-height: 2;
}
#buttonContainer{
display: flex;
justify-content: center;
margin: 100px auto;
text-align: center;
}
#buttonContainer button{
padding: 10px 20px;
width: 100px;
height: 50px;
background: turquoise;
font-weight: bold;
border: none;
border-radius: 10px;
margin: 15px;
cursor: pointer;
color: rgba(37, 37, 36);
}
#buttonContainer button:hover {
background: rgb(17, 199, 84);
transition: ease-in-out 0.5s;
}