samedi 21 janvier 2017

Comparison always false when adding two random numbers and comparing the sum with user input

What I am trying to do is to randomize and assign two numbers to variables and add them while displaying the variables to the user. User enters the sum of the two variables and if the input and the sum is the same, user wins. Though, when I compare, the result is always false when I used console.log to see the Boolean value. I am using html and JavaScript. Here is my code:

<html>
<head>
<title>
Game A
</title>
<script>
var y = parseInt(Math.floor(Math.random()*20));
var z = parseInt(Math.floor(Math.random()*20));
function myFunction() {
var p = parseInt(document.getElementById("demo"));
var z = parseInt(p);
var x = parseInt(y) + parseInt(z);
var q = parseInt(x);
console.log(z===q?true:false);
if(z===q){
alert("Good job!");
}
else{
alert("aw, try again!");
}
}
</script>
</head>
<body>
<p>Click the button to calculate x.</p>
<br/>
<div id="a" style="display:inline-block;heigh:100px;width:100px;">
<script>
document.getElementById('a').innerHTML= y;
</script>
</div>
<div id="b" style="display:inline-block;heigh:100px;width:100px;">
<script>
document.getElementById('b').innerHTML= z;
</script>
</div>
<input id="demo"></input>
<button onclick="myFunction()">Try it</button>

</body>
</html>




Aucun commentaire:

Enregistrer un commentaire