Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript prompt number and continue prompting if answer is wrong

I need prompt the visitor for an integer between 1 and 100 and to continue prompting until a valid number is entered.

Here is what I have:

<script>

var number = parseInt(prompt("Please enter a number from 1 to 100", ""));

if (number < 100) {
    document.write("Your number (" + number + ") is matches requirements", "");
} else if (isNaN(number)) {
    parseInt(prompt("It is not a number. Please enter a number from 1 to 100", ""));
} else {
    parseInt(prompt("Your number (" + number + ") is above 100. Please enter a number from 1 to 100", ""));
}

</script>

It recognizes the number but fails to re-ask when the number is wrong. Can you please help me and explain what you added?

Thank you very much.

like image 267
Art Avatar asked Feb 23 '13 23:02

Art


3 Answers

Something like this should do the trick:

do{
    var selection = parseInt(window.prompt("Please enter a number from 1 to 100", ""), 10);
}while(isNaN(selection) || selection > 100 || selection < 1);
like image 124
Rob M. Avatar answered Nov 19 '22 08:11

Rob M.


Here's a recursive approach:

var number = (function ask() {
  var n = prompt('Number from 1 to 100:');
  return isNaN(n) || +n > 100 || +n < 1 ? ask() : n;
}());
like image 45
elclanrs Avatar answered Nov 19 '22 09:11

elclanrs


Another approach:

<html>
    <head> </head>
    <body onload="promptForNumber();">


<script>
    function promptForNumber( text)
{
    if(text == '' ){
     text = "Please enter a number from 1 to 100";   
    }
    var number = parseInt(window.prompt(text, ""));
    checkNumber(number);

}
function checkNumber(number){

    if (number <= 100 && number >= 1) {
    document.write("Your number (" + number + ")  matches requirements", "");
} else if (isNaN(number)) {
    promptForNumber("It is not a number. Please enter a number from 1 to 100", "");
} else {
    promptForNumber("Your number (" + number + ") is not between 1 and 100", "");
}

}


</script>

    </body>
</html>
like image 1
Nishanth Nair Avatar answered Nov 19 '22 08:11

Nishanth Nair