HTML and CSS Reference
In-Depth Information
EXAMPLE
13.19 (
CONTINUED
)
else{
tries++;
4
alert(tries + " Wrong. Try again.");
form.tfield.value=""; //
Clear the textbox
form.tfield.focus();
//
Put the cursor in the textbox
}
}
// End hiding from old browsers -->
</script>
</head>
<body bgcolor="lightgreen"
5
onLoad="randomize()
"> <!--
Call function when page is loaded-
->
<center>
<b>Pick a number between 1 and 10</b>
<form name="myform">
6
<input type="textbox" size=4
name="tfield" />
<p>
7
<input type="button"
name="button1"
8
value="Check my guess"
onClick="guessit(this.form)
" /> </p>
</form>
</body>
</html>
__________________
This script was modified from one written by Andree Growney originally available at
EXPLANATION
1
A function called
randomize()
is defined. It will create a random number by divid-
ing the number of seconds by 10 and returning the remainder (modulus); for ex-
ample, 59/10 would return the number 9. Then, by adding 1 to that, we get 10.
2
The function called
guessit
will take one argument, a reference to the form. Its
purpose is to see if the number entered by the user,
form.tfield.value
, matches the
value of the random number calculated in the
randomize()
function.
3
The
focus()
method puts the cursor in the text field.
4
If the user guessed wrong, the alert dialog box appears and tells him or her so, the
text field is cleared, and focus is put there.
5
Once the document has loaded, the
onLoad
event handler is triggered, causing
the function
randomize()
to be called. This sets the initial random number for
the program.
Continues