I am trying to learn Javascript and was making a simple math question problem and was trying to make a function to score right answers and wrong answers, but I can't figure out how to pass any information out of my function to permanently keep a score. Can anyone help me?
<html> <body> <p id="question"></p> <input id="answerBox" type=number> <button onclick="checkAnswer()">Answer</button> <p id="answer"></p> <p id="score"></p> <p id="newQuestion"></p> <script> //create MathAddition Problem; var mathAdd = function(x, y) { return x + " + " + y + " = " } //set random numbers; var x = Math.floor((Math.random()*10)+1); var y = Math.floor((Math.random()*10)+1); var z = x + y console.log(z) //Call mathAdd function; document.getElementById("question").innerHTML=mathAdd(x, y); //Check Answer var checkAnswer = function() { var answer=document.getElementById("answerBox").value; if(answer == z) { document.getElementById("answer").innerHTML=answer + " is correct"; document.getElementById("score").innerHTML="Your score is improving" ; } else { document.getElementById("answer").innerHTML=answer + " is not correct"; document.getElementById("score").innerHTML="Your score is dropping. Work harder!" ; } document.getElementById("newQuestion").innerHTML="<a href='test7.html'>Next Question</a>" } </script> </body> </html>
Just add a variable score
that increments each time the answer is correct. Something like this:
var score = 0;
//Check Answer
var checkAnswer = function() {
var answer = document.getElementById("answerBox").value;
if (answer == z) {
score++;
document.getElementById("answer").innerHTML = answer + " is correct";
document.getElementById("score").innerHTML = "Your score increased to " + score;
}
else {
score--;
document.getElementById("answer").innerHTML = answer + " is not correct";
document.getElementById("score").innerHTML = "Your score dropped to " + score + ". Work harder!" ;
}
document.getElementById("newQuestion").innerHTML = "<a href='test7.html'>Next Question</a>"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.