'Question index not updating when I click next button
I have written this code its just that when I click the next button the questions and answers don't update and go to the next question in the array, but it shows the first question and answers when the page loads. I'm not sure what I havent done here.
const questiontext= document.getElementById('question-text');
const A= document.getElementById('OptionA');
const B= document.getElementById('OptionB');
const C= document.getElementById('OptionC');
const D= document.getElementById('OptionD');
const options= document.getElementsByClassName('options');
const nextbutton= document.getElementById('next');
const submitbutton= document.getElementById('submit');
const questions=[
{
question: "What is the best item at mcdonalds?",
answerA: "Fries",
answerB: "Big Mac",
answerC: "Mcnuggets",
answerD: "Quarter Pounder",
correctanswer: "Big Mac"
},
{
question: "What is the cheapest thing on the mcdonalds menu?",
answerA: "Fries",
answerB: "Double Cheeseburger",
answerC: "Happy Meal",
answerD: "Orange juice",
correctanswer: "Fries"
},
{
question: "What is the least popular item at mcdonalds?",
answerA: "Filet O Fish",
answerB: "Hamburger",
answerC: "Veggie Deluxe",
answerD: "Mineral water",
correctanswer: "Filet O Fish"
},
{
question: "How many dips are you allowed with 20 Mcnuggets?",
answerA: "2",
answerB: "4",
answerC: "3",
answerD: "6",
correctanswer: "4"
}
];
//Question index at start
const questionindex= 0;
const currentquestion= () =>{
questiontext.innerHTML= questions[questionindex].question;
A.innerHTML= questions[questionindex].answerA;
B.innerHTML= questions[questionindex].answerB;
C.innerHTML= questions[questionindex].answerC;
D.innerHTML= questions[questionindex].answerD;
if(questionindex === questions.length){
submitbutton.classList.remove('hidden');
}
}
const nextquestion= () =>{
questionindex++
}
//Load first question and answers
currentquestion(questionindex);
//Button to display next question
nextbutton.addEventListener('click', nextquestion);
Solution 1:[1]
change the const and replace it with a let or var
Solution 2:[2]
Change
const questionindex
to
let questionindex
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | daniel asakpa |
| Solution 2 | Slava Rozhnev |
