Adding Dynamic Behavior to Forms
Assume the following form has been created:
Here is the code that produced this form:
<FORM>
<INPUT TYPE=text
NAME=myTextBox
SIZE=30>
<P>
<INPUT TYPE=button
VALUE="myButton"
onclick="myFunction(this.form)">
</FORM>
When the button is clicked, a function named
"myFunction"
is called - and told to operate on this form. The argument
"this.form" is
passed to
myFunction so
it knows to use the current form.
Here is some code for
"myFunction":
function myFunction(form) {
form.myTextBox.value = ""
return ""
}
Notes:
- myFunction
knows it is operating on the form that is passed to
it.
- myFunction
refers to this form internally as
form. (NOT
as
this.form)
- every text box defined in the form has a name
(e.g.,
"myTextBox")
Retrieve the value of
myTextBox
by using
form.myTextBox.value
inside the function body.
- In this example, the null value
("") has
been assigned to
myTextBox,
so the text box will be cleared.
- If you want to assign the value
2 to
myTextBox
instead, use
form.myTextBox.value = 2
- If you want to change the value of
myTextBox
to a positive number when the number in
myTextBox
is negative, use
var x = form.myTextBox.value
if( x < 0 )
form.myTextBox.value = -x
Instructing Your Page to Run a Function Continuously:
function Cycle(form) {
...
setTimeout("Cycle(form)",1000)
return ""
}
Notes:
- The setTimeout
function tells your browser to execute the
given instructions (e.g.,
Cycle(form))
after waiting a given amount of time in milliseconds
(1000
milliseconds =
1
second).
- When referred to from inside your function,
pass form
as an argument to
Cycle.
Instructing your page to run your function as soon as the page is
loaded:
<BODY onLoad="Cycle(document.form[0])")
<FORM>
...
</FORM>
</BODY>
Notes:
- The first form in your document is
form[0],
the next is
form[1],
etc.
- When referred to from the
<BODY> of
the page, (but not from inside the
<FORM> itself),
the argument
document.form[0]
is used so the function knows which form to operate
on.
Using random numbers to generate random events:
- The method
math.random() returns
a random value in the range
(0,1).
- To generate the value "Hello" 30% of the time,
and the value "Goodbye" 70% of the time, this code will do the
trick:
var output
if( Math.random() < 0.3 )
output = "Hello"
else
output = "Goodbye"
- This code will generate the value "Hello" 30%
of the time, "Goodbye" 50% of the time, and "What?" the remaining
20% of the time:
var x = Math.random()
if( x < 0.3 )
output = "Hello"
else if( x < 0.8 )
output = "Goodbye"
else
output = "What?"
- Note: We store the value returned by
Math.random()
in a variable
x because
we use it more than once; we don't want to generate a new random
value each time.
- Note: The second conditional compares
x with
0.8, NOT
0.5. This
means that if
x is
between 0.3
and 0.8
(which occurs about 50% of the time), we return
"Goodbye".