JSFiddle - React, Tailwind, and code Playground
HTML
<div id="quiz">
<label>
<p id="question"></p>
<select id="answers">
</select>
</label>
<button id="submit">Check Answer</button>
<p id="yourAnswer"></p>
</div>
JavaScript
var allQuestions = [
{
question: "Who is Prime Minister of the United Kingdom?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer: 0
}
];
document.getElementById('question').innerHTML = allQuestions[0].question;
for (i=0; i < allQuestions[0].choices.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = allQuestions[0].choices[i];
document.getElementById('answers').appendChild(opt);
}
function checkAnswer(){
var myAnswer = document.getElementById('answers');
var answer = myAnswer.options[myAnswer.selectedIndex].value;
if( answer === 'David Cameron' ) {
document.getElementById('yourAnswer').innerHTML = 'Correct!';
}
else {
document.getElementById('yourAnswer').innerHTML = 'Sorry that\'s incorrect';
}
}
var sub = document.getElementById('submit');
sub.addEventListener('click', checkAnswer, false);