I need to be able to only enter the numbers 1 through to 9 in my prompt window. At the moment, I can enter any character I want and it will still work. How do I restrict this to numbers only? Here is the code I have so far:
<html>
<head>
</head>
<body>
<button onclick="myFunction()">Start Game</button>
<button>Stop Game</button>
<br/>
<br/>
<p><font size="20">Your chosen number is:</font></p>
<span id="number"></span>
<br/>
<br/>
<p><font size="20">Your score so far is:</font></p>
<br/>
<span id="gamedisplay"></span>
<span id="gamedisplay2"></span>
<span id="gamedisplay3"></span>
<span id="gamedisplay4"></span>
<script>
function myFunction() {
var integer = prompt("Please enter an integer between 1 and 9");
if (integer != null) {
document.getElementById("gamedisplay").innerHTML =
Math.floor(Math.random() * 10);
document.getElementById("gamedisplay2").innerHTML =
Math.floor(Math.random() * 10);
document.getElementById("gamedisplay3").innerHTML =
Math.floor(Math.random() * 10);
document.getElementById("gamedisplay4").innerHTML =
Math.floor(Math.random() * 10);
}
}
</script>
</body>
</html>
prompt returns a string, you need to check whether that string is a number or not. Number.isInteger could help, or check against a regexp, or parseInt()?
function getNumber () {
let someNumber = prompt('enter a number from 1 to 9');
for(;;) {
if (someNumber !== '' && typeof Number(someNumber) === 'number' && someNumber < 10 && someNumber > 0){
//do something here
return Number(someNumber);
}else{
//do something else here
someNumber = prompt('Please, enter a number from 1 to 9');
}
}
}
here i check is that not an empty string and type of its value is a number, and that number is bigger than 0 and less than 10; if all is ok, i return value and stop the loop, if not - asking one more time for number
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.