Reputation: 3187
So upon learning a few JavaScript functions, I wanted to make a guessing game, this is my code: (EDITED)
<body>
<script>
var a;
function rand(){
var a = Math.floor((Math.random()*100)+1);
}
function random() {
guess = document.getElementById('gess').value;
if(guess < a) {
document.getElementById('gus').innerHTML = 'To small!';
}
else if(guess > a) {
document.getElementById('gus').innerHTML = 'To big!';
}
else if(guess == a) {
document.getElementById('gus').innerHTML = 'Correct! The secret number is ' + a;
}
}
</script>
<h1> Guess the secret number! </h1>
<input type='text' id='gess'>
<input type='button' onClick='random()' value='Guess!'>
<input type='button' value='Reset Number' onClick='rand()'>
<br>
<p id='gus'> </p>
</body>
What do I do, for the random number (a) to stop refreshing every time I click 'Guess', thank you in advance!
Upvotes: 3
Views: 1099
Reputation: 1839
Do this:
var a = Math.floor((Math.random()*100)+1);
function random() {...}
That will store the random number before the random function is called. Otherwise, a
will be reset every time.
Upvotes: 5