I am trying to create a click on a quiz using pure javascript for uni assignment. I have a bunch of sections to make them appear. Each question has a list of 4 (or so) answers that relate to a different type of personality. I intend to save an array of objects to count each selected answer and provide a breakdown of personality types at the end.
I'm stuck in a function now;
- write down the selected data and add it to the response array,
- hide the current question div and
- display next question div
HTML :
<div class="question" id="q1" data-next="q2">
<h2>Question 1:</h2>
<p>Which of the following is your favourite movie? </p>
<ol class="button">
<li data-score="Ninja">Karate Kid</li>
<li data-score="Robot">Wall-E</li>
<li data-score="Pirate">Pirates of the Caribbean</li>
<li data-score="Zombie">Dawn of the Dead</li>
</ol>
</div>
<div class="question" id="q2" data-next="q3">
<h2>Question 2:</h2>
<p>A building is on fire and you hear a child screaming for help from the third floor window. Do you: </p>
<ol class="button">
<li data-score="Ninja">Mysteriously disappear and re-appear with the children</li>
<li data-score="Robot">Run in and save the child on the second floor, because i'm made of metal and fire won't hurt me!</li>
<li data-score="Pirate">Dress up as a pirate and loot the surrounding neighbourhood, including the bank?</li>
<li data-score="Zombie">Eat all the brains. Nom nom uuuuggghhh.</li>
</ol>
</div>
JS:
document.getElementById("beginquiz").addEventListener("click", startQuiz);
function startQuiz () {
document.getElementById("intro").style.display = "none";
document.getElementById("q1").style.display = "block";
}
var answerData = [
{name: "Ninja" , score: 0},
{name: "Robot" , score: 0},
{name: "Pirate" , score: 0},
{name: "Zombie" , score: 0} ]
var buttons = document.querySelectorAll(".button");
for (var i = 0 ; i < buttons.length ; i++) {
buttons[i].onclick = buttonClicked;
}
function buttonClicked() {
var selectedType = this.dataset.score;
answerData["selectedType"].score++;
this.parentElement.style.display = "none";
var nextQuestion = this.parentElement.dataset.next;
document.getElementById(nextQuestion).style.display = "block";
}
Let's say that I have done so far https://jsfiddle.net/funkefiddle/e1za0gtr/1/
- , . , , . Firefox "this.dataset.score is undefined".
var selectedType = this.dataset.score.value;
answerData["selectedType"].score++;
, .
- , , . , .
: .value, , .
, nextQuestion . / ( answerData.
, , , .
answerData[selectedType].score++ ;