I am trying to make a simple Javascript Quiz with radio buttons. Each question and options should be stored in an array, the questions being replaced dynamically with getElementById(). I am stuck trying to assign values for the radio buttons so that I can display the score at the end.
I am new to javascript and this is the first project I'm working on.
This is what I have so far:
var questionsArray = new Array;
questionsArray[0] = ["1. Who is the president of the US?"];
questionsArray[1] = ["2. What is the capital city of France?"];
questionsArray[2] = ["3. What is your favorite food?"];
var choicesArray = new Array();
choicesArray[0] = ["Lebron James", "Barack Obama", "George Bush"];
choicesArray[1] = ["Nairobi", "London", "Paris"];
choicesArray[2] = ["Pizza", "Sushi", "Pasta"];
var i = 0;
var theScore = 0;
function btnOnclick() {
var radElement = document.form1.options;
var showDiv = document.getElementById("questionsDiv");
showDiv.className = "showClass";
document.getElementById("next").value = "Next";
while(i < questionsArray.length && i < choicesArray.length) {
var currQues = questionsArray[i];
var option1 = choicesArray[i][0];
var option2 = choicesArray[i][1];
var option3 = choicesArray[i][2];
i++;
document.getElementById("question").innerHTML = currQues;
document.getElementById("choice1").innerHTML = option1;
document.getElementById("choice2").innerHTML = option2;
document.getElementById("choice3").innerHTML = option3;
return true
}
if(questionsArray[0] && radElement[1].checked == true) {
theScore += 10
} else {
theScore += 0
}
if(questionsArray[1] && radElement[2].checked == true) {
theScore += 10
} else {
theScore += 0
}
if(questionsArray[2] && radElement[1].checked == true) {
theScore += 10
} else {
theScore += 0
}
alert(theScore)
}
function bodyOnload() {
var hideDiv = document.getElementById("questionsDiv");
hideDiv.className = "hideClass";
document.getElementById("next").value = "Start Quiz"
}
.hideClass{
display: none;
}
.showClass{
display: block;
}
<body onload="bodyOnload()">
<h1>QUIZ</h1>
<div id="questionsDiv">
<form name="form1">
<p id="question" class="showQuestion"></p>
<tr>
<span id="choice1"></span>
<td>
<input type="radio" id="radio1" value="0" name="options" />
</td>
<td>
<span id="choice2"></span>
<input type="radio" id="radio2" value="0" name="options" />
</td>
<td>
<span id="choice3"></span>
<input type="radio" id="radio3" value="0" name="options" />
</td>
</tr>
</div>
<br />
<br />
<hr>
<tr>
<td>
<input type="button" id="next" value="Next" name="nextButton" onclick="btnOnclick()"/>
</td>
</tr>
</form>
</body>
Aucun commentaire:
Enregistrer un commentaire