Ruben Westermann Ruben Westermann - 3 months ago 10
HTML Question

Im making a program that makes random math, but it does not work

So this is the program:



<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<input type="number" id="myNumber" value="">
<button onclick="Kaas()">Controleer</button>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>

<script>
var z= 0;
function myFunction() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demo").innerHTML = x;
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demo2").innerHTML = y;
var z = x-y
document.getElementById("demo3").innerHTML = z;
}

var a=0;
function Kaas() {
var x = document.getElementById("myNumber").value;

if(x==z){
document.getElementById("demo4").innerHTML = "Correct";
}else{
if(a==3){
document.getElementById("demo4").innerHTML = "Fout, het goede antwoord is" + z;
}else{
document.getElementById("demo4").innerHTML = "Fout, probeer het nog een keer";
a +=1;
}
}
}
</script>
</body>
</html>





But it isn't working. I was trying to make it so I type in the correct answer and then it would say correct or incorrect.

Also I wanted it to say the correct answer after 3 times.

Answer

You are redefining z variable as local. Outer was never changed.
Just remove var before z inside your function:

var z= 0;
function myFunction() {
  var x = Math.floor((Math.random() * 10) + 1);
  var y = Math.floor((Math.random() * 10) + 1);
  z = x - y;
  document.getElementById("demo").innerHTML = x;
  document.getElementById("demo2").innerHTML = y;
  document.getElementById("demo3").innerHTML = z;
}

var a=0;
function Kaas() {
  var x = document.getElementById("myNumber").value;
  if (x==z) {
    document.getElementById("demo4").innerHTML = "Correct";
  } else {
    if (a==3) {
      document.getElementById("demo4").innerHTML = "Fout, het goede antwoord is" + z;
    } else {
      document.getElementById("demo4").innerHTML = "Fout, probeer het nog een keer";
      a += 1;   
    }
  }
}
<button onclick="myFunction()">Try it</button>
<input type="number" id="myNumber" value="">
<button onclick="Kaas()">Controleer</button>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>