I've been trying to debug this for a couple of days...cannot see why it performs the way it does. Help is much appreciated.
Forgive me about how lengthy the assignment details are.
-Create a function named whileTest(). Inside the function, create a variable named number and assign it a value between 1 and 10.
-Create another variable named answer and assign it a value of 0 (zero).
-Then create a while loop. Create code that will cause the loop to execute as long as the number variable does not equal the answer variable.
-Inside the loop, assign the answer variable the return value from a prompt dialog box.
-The prompt will ask the user to guess a number between 1 and 10. The loop will continue until the proper answer is entered.
-After the loop exits, use an alert dialog box to inform the user of a correct guess.
-Once you have the code working properly, create code that will allow the user only three guesses. If, after three guesses, the user has not entered the correct answer, exit the function and alert the user that he or she is out of guesses via an alert dialog box.
-Ensure that only one dialog box appears after the function is exited, one with a correct guess message, or one asking the user to try again.
-Experiment with different methods that you have seen for calling the function. You can use the load event or the onclick event handler of a form button.
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>While Test</title>
<script type="text/javascript">
function whileTest()
{
var number = 5;
var answer = 0;
var chances = 0;
answer = prompt('Guess a number between 1 and 10. ');
//I've tried the if statement for correct choice here...page doesn't load.
while(answer != number)
{
answer = prompt('Wrong! Please Guess Again! ');
chances++
if(answer == number && chances >=1)
{
alert('You have chosen correctly!! ');
return;
};//Works here, but if the first guess is correct, page stops loading.
if(chances == 2)
{
alert('You have guessed incorrectly 3 times...Goodbye! ');
return;
};
//Any time I try to use an if statement outside of the while loop,
//the page will not load, or doesn't load anything. I can't understand why.
};
};
</script>
</head>
<body onload="whileTest()">
</body>
</html>