EIW Fall 2005 : calc Javascript Source


<html>
<head>
 <title>Javascript Calculator/Validation</title>
</head>
<body>

<script>
// calculates the sum and product of fields x and y

function calc() {
   // get objects that correspond to our fields
   var   x_field = document.getElementById("x");
   var   y_field = document.getElementById("y");
   var   sum_field = document.getElementById("sum");	
   var   product_field = document.getElementById("product");

   // get the actual values from these fields
   var x = parseFloat(x_field.value);
   var y = parseFloat(y_field.value);

   if ( isNaN(x) || isNaN(y)) { 
      alert("Try giving me some numbers!");
      return;
   }

   // compute the sum and product
   var sum=x+y;
   var product=x*y;

   // update the form so that is shows the results 
   // use format with 2 places to the right of the dec. point	
   
  sum_field.value = Math.round(sum*100)/100;
  product_field.value = Math.round(product*100)/100;
}
</script>

<h2 style="text-align: center; color: black">Javascript Calculator</h2>
<hr/>
<center>
<form>
<table bgcolor="black" cellpadding="2"><tr><td>
<table bgcolor="wheat" cellspacing="10">
<tr>
  <td>Value for X</td>
  <td><input type="text" id="x" /></td>
</tr>

<tr>
  <td>Value for Y</td>
  <td><input type="text" id="y" /></td>
</tr>

<tr><td colspan="2"><hr/></td></tr>
 <tr>
  <td>Sum: X+Y:</td>
  <td><input type="text" id="sum" /></td>
</tr>

<tr>
  <td>Product X*Y:</td>
  <td><input type="text" id="product" /></td>
</tr>

<tr >
<td colspan="2" width="100%">
<input type="button" value="Press to calculate"  onclick="calc();" >
</td></tr>
</table>
</td></tr></table>
</form>
</center>