| This example illustrates
a little of JavaScript's mathematical abilities. It also shows how you
can use a form for input/output with JavaScript without having to submit
the form to a server.
The code that lets us create this mini-calculator is:
<FORM>
<INPUT
TYPE="text"
NAME="number"
VALUE="25">
<INPUT
TYPE="text"
NAME="answer">
<INPUT
TYPE="button"
NAME="sqrt"
VALUE="SqrRt"
onClick= "form.answer.value=Math.sqrt(form.number.value)">
<INPUT
TYPE="button"
NAME="square"
VALUE="x ^ 2"
onClick= "form.answer.value=Math.pow(form.number.value,
2)">
</FORM>
NOTES:
- A form element named abc can be accessed through
JavaScript as form.abc (if the form is given a name, say
"stuff" in the <FORM>
tag, this name can also be used to access a form element, e.g.,
stuff.abc.
- The value of some elements, for example of text input elements,
can not only be accessed but also changed via form.abc.value.
- <INPUT
TYPE="button"
NAME="sqrt"
VALUE="SqrRt"
onClick=
"form.answer.value=Math.sqrt(form.number.value)">
adds a button form element named "sqrt"
to the form; "SqrRt" is the
label of the button. When the button is clicked JavaScript takes the
value in the form element named "number"
(i.e., form.number.value) and passes that number to Math.sqrt.
The value returned is just the square root of the argument. This is
then assigned to form.answer.value,
setting the value of the "answer"
element (input box) in the form.
- The onClick
for the button named "square" works similarly, except that
it passes the value entered in the form's "number"
element to the pow method of the Math
Object (i.e., to Math.pow). This object
takes two arguments and raises the first argument to the power of
the second.
Thus a number may be entered into the form's "number"
element. When one of the buttons is pressed, the number's square root or
square is calculated, depending on which button is pressed. The results
of the calculation are displayed in the form's "answer"
element.
With a little more work, you can even create a real JavaScript calculator. |