I have to make a trivia webpage where you have a question with answers displayed on screen, with 10 questions to cycle through.
I have an array from a json file which contained the info.
I bring in the info, grab the first question, and the related options and if the answer is correct (all stored in the array)
in a for each loop, create an eventlistener, when a button is pressed, checks if the option is correct or not, add score then does a finishcheck.
which increases index, check if the new index is iwthin the length of the questions – prints next question, and send back to the loop.
else it shows the finals score.
the issue is that my index is doubling. in the html console the questions related to each index is printed. so it’s cycling through each index, printing the answers but only allowing answers to questions 1,2,4,8 are ever shown on screen.
changed this.index to all the methods off incrementing, ++, += 1, i = i + 1.
if i take out the loop() from the finishcheck, it increments 1 by 1 normally,
tried adding a second event listener to o, to initiate the finishcheck function to no avail.
finishCheck() {
this.index += 1;
if (this.index < this.questions.length) {
this.showQuestion();
this.loop();
} else {
this.showScore();
this.hideAnswers();
}
}
loop() {
const h = document.querySelectorAll(".btn-primary");
h.forEach((o, i) => {
o.innerHTML = this.questions[this.index].options[i].option;
console.log(this.questions[this.index].options[i].option);
o.addEventListener("click", () => {
if (this.questions[this.index].options[i].isCorrect) {
this.score++;
}this.finishCheck();
});
}
);
}
2
Answers
You can use below iteration mechanism to iterate over questions and apply click handler to individual button that won’t call same handler again and increment the index..
This is a WAY overblown answer but I decided to have some fun.
Here I created a class and created questions an answers which show when I make a choice change.
Notice how I loop through the questions and add new
select
options based on questions and then the options for each.As a bonus I show how to add a new question once my class instance is created.
Notice how I add event listeners to the dynamically create elements and also trigger custom events when a change is made to do validation (not fancy) of the choice, then set a dataset value which is used in the CSS just for fun.