by

Calling a Javascript Function from an HTML Form

The HTML and javascript code below demonstrates how to use a value entered into an HTML form to perform a calculation and return the result. This example simply squares the input value. Some simple checking is performed to ensure that the input value is a number. The following form demonstrates the code in action.
 

Input Number:
Input Squared:

 

Here is the code.

<script type='text/javascript'>
function processInput() {
var myVars=document.getElementById('myTable');
var myInput=myVars.input.value;
if (isNaN(myInput)) {
myVars.output.value = "Not a valid input";
}
else {
myVars.output.value = Math.pow(myInput,2);
}
return false;
}</script>

<form id="myTable" action="#">
<table border="1" align="center">
<tbody>
<tr>
<td align="right">Input Number:</td>
<td align="left"><input type="text" name="input" size="64"
onkeyup="processInput()" /></td>
</tr>
<tr>
<td align="right">Input Squared:</td>
<td><input type="text" name="output" readonly="readonly" size="64" /></td>
</tr>
</tbody>
</table>
</form>

 

Leave a Reply

Your email address will not be published. Required fields are marked *