...

View Full Version : Function not defined error in basic program



timo1023
09-13-2008, 02:36 AM
Just learned javascript today, and I just can't get my head around why this program doesn't work. Here is a link (http://textsnip.com/921b5e/jscript) to the code (syntax colored, numbered, etc.)

The code is just to play a number guessing game. I have two functions, playGame() and guessfunction(). playGame() just starts playing the game,and when the user clicks the button, it calls guessfunction(), which checks to see how the answer relates to the random number generated at the beginning (>,<,=, etc). If the guess and the random number aren't equal, it calls playGame() again. However, once playGame() gets called a second time, I get a "function not defined" error for guessfunction(). Why is this occuring?

jmrker
09-13-2008, 03:27 AM
Can you post your script. The link is helpful but it does not contain your problem.

grink
09-13-2008, 03:50 AM
As an aside, your random number guesser chooses between 0 and 100.

You want to do this instead:


var randomnumber=Math.floor(1 + Math.random()*100);

timo1023
09-13-2008, 03:55 AM
Can you post your script. The link is helpful but it does not contain your problem.

The link is the code for my entire index.html file. There isn't another script or any other code.

Arty Effem
09-13-2008, 04:10 AM
If the guess and the random number aren't equal, it calls playGame() again. However, once playGame() gets called a second time, I get a "function not defined" error for guessfunction(). Why is this occuring?Because use of document.write after the document has finished loading, overwrites the existing content.
Re-structure the program so that the form is only written once.

timo1023
09-13-2008, 07:58 AM
Great, thanks guys, I got it working.

I ended up writing "too high" or "too low" to an input text box. Is there a way to write text to the screen without overriding everything else and without writing to a form value?

Philip M
09-13-2008, 09:41 AM
Great, thanks guys, I got it working.

I ended up writing "too high" or "too low" to an input text box. Is there a way to write text to the screen without overriding everything else and without writing to a form value?


<div id = "mydiv"></div>

<script type = "text/javascript">
if (chosenNumber < correctNumber) {
document.getElementById("mydiv").innerHTML = "Too low!";
}
if (chosenNumber > correctNumber) {
document.getElementById("mydiv").innerHTML = "Too high!";
}
if (chosenNumber == correctNumber) {
document.getElementById("mydiv").innerHTML = "You got it!";
}
</script>

Naturally chosenNumber and correctNumber need to be changed to the actual names of the relevant variables.


The Pastor will preach his farewell message, after which the choir will sing "Break forth into Joy" - Church bulletin



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum