JSFiddle - React, Tailwind, and code Playground
by John Nieves
JavaScript
var allQuestions = [{
question: "Who is Prime Minister of the United Kingdom?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer: 0
}];
var question = document.createElement('div');
question.innerHTML = allQuestions[0].question;
document.body.appendChild(question);
var choices = allQuestions[0].choices;
for (var i = 0; i < choices.length; i++) {
var choiceButton = document.createElement('button');
choiceButton.onclick = checkAnswer;
choiceButton.id = i;
choiceButton.className = "answer";
choiceButton.innerHTML = choices[i];
document.body.appendChild(choiceButton);
}
function checkAnswer(){
var id = event.target.id;
var chosen = document.getElementById(id);
if (chosen.id == allQuestions[0].correctAnswer) {
console.log("Correct!");
} else {
console.log("Incorrect");
}
}