Interacting with Your Program
In the examples given so far, the program is loaded into a
browser, runs, and diplays its answers. If you want to change
numbers in the program, for example, you have to open it in an
editor and change the .html file. This is not always convenient.
JavaScript provides many ways in which the user can interact
with a program, and for example, change the values which
it uses for variables. Some of these are rather complicated,
so we will show only the simpler methods here.
The simplest kind of interaction is shown
in this program.
If you look carefully at what happens here, you will see that
the program in fact stops and waits for the button to be clicked.
This the function use:
alert('some message')
displays the message and causes the program to wait until the button is clicked.
A more useful kind of interaction is illustrated
here.
An instruction such as:
... = prompt ("Message", default)
has the following effect.
- A popup appears with the message "Message" in it, a type-in
box and some buttons.
- The type-in box initially contains whatever value the second
argument of the function (default) is set to. In the example this
is an empty string "" so that the box is blank.
- When the OK button is clicked anything that has been put in the
type-in box is assigned to the variable (in the example, x)
on the left of the equals sign in the instruction.
The default argument is useful if there is a most likely
value for what is to be typed. This saves the user typing it in,
you can just click OK. If the value needs to be changed, click Clear
and type in the new one.
Try it with this program.
Here is the
resonance program modified to let the user enter values using
prompt.
Still more here...