For the following code below. When the user is prompted to ask for the \'size\'
ID: 3586468 • Letter: F
Question
For the following code below. When the user is prompted to ask for the 'size' I only want a numerical value to be accepted (example if the user enters "X" a pop-up will be shown saying invalid option, chose a number. '4' gets entered and the program continues down) I assume an If statement is needed but not entirely sure how to input that..
<html>
<head>
</head>
<title> Test page</title>
<body>
<p id ="myParagraph">
</body>
<script>
var size = prompt('Enter a size');
var inputA = prompt ('Enter favorite Animal');
var inputB = prompt ('Enter number value of how many you want');
var inputC = prompt ('Enter favorite color');
var art = [];
for (var x = 0; x < size; x++){
for (var y = 0; y < size; y++){
if ((x+y)%2 !=0 ){
art += inputA + ' ' ;
}else{
art += inputB + ' ';
}
}
art += inputC + '<br>';
}
document.getElementById('myParagraph').innerHTML += '<br>' + art;
</script>
</html>
Explanation / Answer
Just add this condition out there in place of the line var size = prompt('...');
var size = prompt('Enter a size'); //Reads an integer.
while(Number(size) != size) //If the numeric value is equivalent to what you entered.
{
document.write("Please enter an integer."); //Reprompt.
size = prompt('Enter a size');
}
document.write("Size: " + size);