|
|
||||||||||
|
|
Javascript | Math & Forms |
|
|
|
||||||
Math & FormsCalculate 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:
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.
|
||||||||||
|
|
||||||||||