JSFiddle - React, Tailwind, and code Playground
by medusae
HTML
<body>
<div id="questions"></div>
<div id="words"></div>
<input type="button" value="VOTE" onClick="checkQuestions()" />
</body>
JavaScript
var allQuestions = [{question: "Who is Prime Minister of the United Kingdom?", choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"], correctAnswer:0},
{question: "How many toes??", choices: ["1", "2", "3", "5"], correctAnswer:3},
{question: "Who is Kanye West' daughter?", choices: ["North", "West", "South", "East"], correctAnswer:0}];
//you can access checkbox name through an array
//match array number to number in allQuestions array
var questionNum = 0;
var scoreNum = 0;
var makeQuestions = "";
$(document).ready(function() {
makeQuestions = function() {
if(questionNum === allQuestions.length){
$("input[value=VOTE]").remove();
$("#questions").text(" Done! Your score is" + " " + scoreNum);
}
else{
$("#questions").text(allQuestions[questionNum].question);
for(var i=0; i<allQuestions[questionNum]['choices'].length;i++){
$('#words').append('<input type="radio" name="buttons">' + allQuestions[questionNum]['choices'][i] + '</input');
}
}
}
makeQuestions();
});
var checkQuestions = function() {
var lenG = document.getElementsByName("buttons").length;
console.log(lenG);
var rightAnswer = allQuestions[questionNum]['correctAnswer'];
for (var i=0; i<lenG; i++){
if (document.getElementsByName("buttons")[i].checked === true) {
console.log(i);
console.log(document.getElementsByName("buttons")[i].checked);
//compare value to what was inputted
if(i === rightAnswer){
scoreNum +=1;
alert("Correct! Your score is" +" " + scoreNum);
}
else{
alert("False! Your score is still"+ " " + scoreNum );
}
}
}
questionNum = questionNum +1;
$("#words").empty();
makeQuestions();
}