Javascript
Math & Forms
Javascript & Objects |
OnLoad & OnUnLoad |
OnMouseOver |
Math & Forms |
The Date Object |
Opening New Browser Windows |
Javascript Caveats
Calculate the Square
or Square Root
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 method="POST"
enctype=application/x-www-form-urlencoded>
Enter a number here:
<input name="number" type="INT" size=10 value="0">
<p>
Press button of function to perform:
<input name="sqrt" value="SqrRt" type="BUTTON"
Onclick =
"form.answer.value=Math.sqrt(form.number.value)">
<input name="square" value="x**2" type="BUTTON"
Onclick =
"form.answer.value=Math.pow(form.number.value,2)">
<p>
Result:
<input name="answer" type="INT" value="0"> <br>
</form>
Notes:
- The HTML <form>
tag corresponds to the Javascript form object.
- 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. (Again,
the form name can be used here if it has one.)
-
<input name="sqrt" value="SqrRt" type="BUTTON"
Onclick = "form.answer.value=
Math.sqrt(form.number.value)">
adds a button-type 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 sqrt
method of Javascript's Math object. 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 (the text box labeled "Enter a number here"). 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 (box next to "Result").
With a little more work, you can even create a real Javascript
calculator.
And here's a page that uses Javascript math methods to convert
between decimal and hexadecimal numbers that you might
find useful, for example in customizing your page colors.
|