Monday, November 9, 2009

Dynamically calculate the sum of fields using JavaScript

For drop-down boxes

Hi,
I've created the code below which automatically adds two fields together (drop-down boxes) , without the need for a submit or input button.

Now, I am trying to do the same again, but this time instead of having drop-down boxes, i need to have text input boxes. (eventually i will be adding monetary values together).

So far, i've not had any luck, but would really appreciate some help or advice.


<script type="text/javascript"> <!--
function updatesum() {
document.form.sum.value =
(
document.form.sum1.options[document.form.sum1.selectedIndex].text-0) +
(
document.form.sum2.options[document.form.sum2.selectedIndex].text-0); }
//--></
script >

<body>
<form name="form" >
Select a number:
<select name="sum1"
onChange="updatesum()">
<option selected>0<option>1<option>2<option>3<option>4
<option>5<option>6<option>7<option>8<option>9
</select>
and another number:
<select name="sum2"
onChange="updatesum()">
<option selected>0<option>1<option>2<option>3<option>4
<option>5<option>6<option>7<option>8<option>9
</select>
Their sum is:</th> <td><input name="sum" readonly style="border:none"
value="0">
</form>
</body>



 

For Text Boxes

Your original script is prone to errors if the user enters a non-number.
See the problem if you enter 'one' instead of '1'.

Here's a slight modification to avoid this problem with a slight change to the function called to avoid one id entry.


 

<html>
<
head>
<
title>Text Summation</title>

<
script type="text/javascript">
function
calc(A,B,SUM) {
  var
one = Number(A);
  if (
isNaN(one)) { alert('Invalid entry: '+A); one=0; }
  var
two = Number(document.getElementById(B).value);
  if (
isNaN(two)) { alert('Invalid entry: '+B); two=0; }
  
document.getElementById(SUM).value = one + two;
}
</script>

<body>
<form name="form" >
Enter a number:
<input name="sum1" id="op1" value="" onChange="calc(this.value,'op2','result')" />
and another number:
<input name="sum2" value="" id="op2" onChange="calc(this.value,'op1','result')" />
Their sum is:
<input name="sum" value="" id="result" readonly style="border:0px;">
</form>

</body>
</html>

0 comments: