Submit article - Sport Betting Systems - Debt Consolidation - Myspace Layouts - Turquoise Jewelry

PDA

View Full Version : dynamically calculate the sum of fields


ian11788
Feb 13th 2007, 8:27 am
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>

----------------

Thanks!

Ian

designcode
Feb 13th 2007, 12:41 pm
Try using following js


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


HTML will be


<body>
<form name="form" >
Enter a number:
<input name="sum1" onChange="updatesum()" />
and another number:
<input name="sum2" onChange="updatesum()" />
Their sum is:</th> <td><input name="sum" readonly style="border:none"
value="0">
</form>
</body>


Not tested but should work. Hope this helps

ian11788
Feb 14th 2007, 1:49 am
Thank-you!

This works fine except it concatenates the two numbers together, so 4+4 gives 44 instead of 8.

I have remedied this by changing the line (added bits in red):

document.form.sum.value = (document.form.sum1.value -0) + (document.form.sum2.value -0); }

... and this now works perfectly.

designcode
Feb 14th 2007, 2:19 am
Oh, i forget that "+" operator is also use to concat variables in JS, please add it to my rep if you find it useful :)

Arnold9000
Feb 15th 2007, 8:40 am
In the future, just parse it to an int before adding

document.form.sum.value = parseInt(document.form.sum1.value) + parseInt(document.form.sum2.value);

Javascript will let you use + as an adder or a string concatenator. It defaults to a string if it's not sure, which is why you get 44 instead of 8