I have a trivia app that has four buttons, each with their own answer. I have implemented getElementById for each button, and have also added "click" event listeners to each one. Upon clicking the button, the function "checkAnswer" runs. This is what the function looks like so far.
function checkAnswer() {
answer = randomQuestion.answers.find((answer) => answer.correct);
if(answer.correct === true) {
console.log("Correct!");
} else {
console.log("Incorrect");
}
}
"randomQuestion" and "answer" are global variables. randomQuestion generates a question from a pool of questions imported from a separate file.
randomQuestion = questions[Math.floor(Math.random()*questions.length)];
I need to find the correct answer and compare it to the selected answer. I think I might need to grab the index of each button, but I am unsure how to do that.
Here is one question from my array of object questions.
export const questions = [
{
question: 'What year did the United State gain independence?',
answers: [
{ text: '1776', correct: true },
{ text: '1876', correct: false },
{ text: '1676', correct: false },
{ text: '1576', correct: false }
]
},