I've been working on creating a quiz with branching logic - you can check out my progress in this Fiddle. I've looked into similar projects like those discussed here and here, but their solutions didn't quite fit what I needed for my quiz since I'm sticking to plain Javascript.
The structure of my quiz employs a tree-like system. For instance, the first question might be about wine preference, leading to further sub-questions based on the initial answer. The ultimate goal is to guide the user toward a specific result.
However, the issue that I'm facing is getting stuck before being able to present the second set of questions and choices.
I suspect that there might be an error within my questions array object variable.
Although I successfully linked my buttons to the initial labels (white and red) inside the beginQuiz function to access the top level of the tree, I encounter difficulties when attempting to delve deeper into the array - resulting in an undefined error message.
For instance (within the showQuestion function):
topBtn.innerHTML = questions[questionIndex].question.choices.label;
bottomBtn.innerHTML = questions[questionIndex].question.choices.label;
After selecting one of the choice buttons, the question area displays 'undefined'.
This is the error thrown: Uncaught TypeError: Cannot read properties of undefined (reading 'question')
While I can successfully fetch the first question and choices using the beginQuiz function, I seem unable to progress to the subsequent set. What could I be missing?
How can I advance to display and interact with the next batch of questions and labels?
Thank you in advance for any assistance provided.
const questions = [
{
question: {
text: 'What type of wine do you like?',
choices: [
{
label: 'white',
path: 1,
question: {
text: 'I prefer...',
choices: [
{
label: 'sparkling',
path: 11,
},
{
label: 'still',
path: 12,
},
],
},
},
{
label: 'red',
path: 2,
question: {
text: 'I prefer...',
choices: [
{
label: 'sparkling',
path: 21,
},
{
label: 'still',
path: 22,
},
],
},
},
],
},
},
];
topBtn.addEventListener('click', nextQuestion);
bottomBtn.addEventListener('click', nextQuestion);
restartBtn.addEventListener('click', restart);
let questionIndex = 0;
function beginQuiz() {
let questionIndex = 0;
questionText.innerHTML = questions[questionIndex].question.text;
topBtn.innerHTML = questions[questionIndex].question.choices[0].label;
topBtn.addEventListener('click', () => {
if (questionIndex < 2) {
nextQuestion();
}
});
bottomBtn.innerHTML = questions[questionIndex].question.choices[1].label;
bottomBtn.addEventListener('click', () => {
if (questionIndex < 2) {
nextQuestion();
}
});
}
beginQuiz();
function showQuestion() {
questionText.innerHTML = questions[questionIndex];
topBtn.innerHTML = questions[questionIndex].question.choices.label;
bottomBtn.innerHTML = questions[questionIndex].question.choices.label;
}
function nextQuestion() {
questionIndex++;
showQuestion();
}