<!-- JavaScript:Forms code snippet 5. -->
<!-- Simple calculator. Using a table for form layout. -->
<!-- Example of use of the keyword 'this' combined with '.form'
to pass an object to a function. -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- Code source: http://www.justfigures.co.uk/ -->
<!-- A resource for web developers using XHTML, CSS, JavaScript, PHP -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View code snippet page</title>
<script language="JavaScript" type="text/javascript">
function a_plus_b(form) {
// convert input to numeric data type with parseFloat()
a=parseFloat(form.a.value)
b=parseFloat(form.b.value)
c=a+b
form.answer.value = c
}
function a_minus_b(form) {
a=parseFloat(form.a.value)
b=parseFloat(form.b.value)
c=a-b
form.answer.value=c
}
function a_mul_b(form) {
a=parseFloat(form.a.value)
b=parseFloat(form.b.value)
c=a*b
form.answer.value=c
}
function a_div_b(form) {
a=parseFloat(form.a.value)
b=parseFloat(form.b.value)
c=a/b
form.answer.value = c
}
function a_pow_b(form) {
a=parseFloat(form.a.value)
b=parseFloat(form.b.value)
// note the use of the 'Math' object
c=Math.pow(a, b)
form.answer.value = c
}
</script>
</head>
<body>
<form name="calculator" id="calculator">
<table>
<tr><td colspan="5">Please enter your numbers here:</td></tr>
<tr><td colspan="5"><input type="text" size="75" value="0" name="a" /></td></tr>
<tr><td colspan="5">and here:</td></tr>
<tr><td colspan="5"><input type="text" size="75" value="0" name="b" /></td></tr>
<tr><td colspan="5">then press the appropriate button to calculate the answer.</td></tr>
<!-- note that 'this.form' is equivalent to 'document.calculator' -->
<tr>
<td><input type="button" value=" + add " onClick="a_plus_b(this.form)" /></td>
<td><input type="button" value=" - subtract " onClick="a_minus_b(this.form)" /></td>
<td><input type="button" value=" x multiply " onClick="a_mul_b(this.form)" /></td>
<td><input type="button" value=" / divide " onClick="a_div_b(this.form)" /></td>
<td><input type="button" value=" ^ power " onClick="a_pow_b(this.form)" /></td>
</tr>
<tr><td colspan="5">answer will appear here:</td></tr>
<tr><td colspan="5"><input type="text" size="75" value="0" name="answer" /></td></tr>
</table>
</form>
</body>
</html>