So, I'm trying to create a quiz in Javascript, by using number ids of the text inputs in HTML, then running a for loop and if to compare the input to the answer in an answers array.
In Html:
<form>
China<input type="text" id="0"><br>
France<input type="text" id="1"><br>
Japan<input type="text" id="2"><br>
<input type="button" id="submitt" value="submit">
</form>
In Javascript:
var answers = ["Beijing", "Paris", "Tokyo",];
$("#submitt").click(function() {
var totalYes=0;
function checkAnswers() {
for(var i=0; i<answers.length; i++) {
var userAnswer = document.getElementById(i);
if(userAnswer.value===answers[i]) {
totalYes++;
}
}
}
alert(totalYes);
checkAnswers();
});
But the code doesn't add 1 to the variable totalYes (questions correct). I've tried totalYes+=1 and totalYes + 1 as well. The alert of totalYes shows up as 0 everytime.
But I know that's the only part not working because when I change totalYes to correct and incorrect alerts, it works:
var answers = ["Beijing", "Paris", "Tokyo",];
$("#submitt").click(function() {
var totalYes=0;
function checkAnswers() {
for(var i=0; i<answers.length; i++) {
var userAnswer = document.getElementById(i);
if(userAnswer.value===answers[i]) {
alert("Correct!");
} else {
alert("Incorrect!");
}
}
}
alert(totalYes);
checkAnswers();
});
Please help?
forloop for each question, any answer can be put into any textbox. Example: Paris can be put in the textbox next to China and you'll still get 1 right.