Reputation: 19
Why won't it call the last if
after going through all the arrays?
//array biblioteket
var startArray = [
{
"s1": "Hvor høj er Rundetårnet? ",
"svar": "34"
},
{
"s1": "hvor gammel er Thomas",
"svar": "27"
}
]
var qu = 0;
var score = 0;
//submit knapper kalder funktion info
$("#form").submit(quiz);
$("#question").html(startArray[qu].s1 + "<br/><br/>");
function quiz() {
var answer = $("#answer").val();
if (answer == startArray[qu].svar) {
score++
$("#comment").html("<h2>" + "Flot arbejde! <br/> <br/>" + "Din Score er: " + score + "</h2>");
qu++
$("#question").html(startArray[qu].s1 + "<br/><br/>");
} else {
$("#comment").html("<h2>" + "prøv igen <br/> <br/> " + "</h2>");
}
if (qu == 2) {
$("#question").hide();
$("#form").hide();
$("#comment").html("Tillykke du er færdig. <br/> <br/>" + "Din Score er: " + score);
}
event.preventDefault();
$("#answer").val('');
}
Upvotes: 1
Views: 76
Reputation: 196092
Change function quiz()
to function quiz(event)
so you have a reference to the event
in the method..
Otherwise your event.preventDefault();
does not work.. (it causes an error as event
is undefined)
You also need to check if there is a next question before trying to show it..
so
qu++;
if (startArray[qu]){
$("#question").html(startArray[qu].s1 + "<br/><br/>");
}
Demo with all changes at http://jsfiddle.net/gaby/Ym5p6/3/
Upvotes: 1
Reputation: 4865
Put ; after qu++ and score++ otherwise qu will not be incremented.
Also you are using incremented qu value in $("#question").html(startArray[qu].s1 + "<br/><br/>");
which will be startArray[2].s1 for second question, however it should be startArray[1].s1 for second question.
So change it to:
$("#question").html(startArray[qu-1].s1 + "<br/><br/>");
and you are good to go.
Upvotes: 1