View Full Version : Javasript and Form Calculation

10-02-2006, 08:35 PM
I have a form that pulls from a database. One of the form values shows a number (percent) for that particular row. I have a variable that adds the form values and then using a cfoutput (I’m using ColdFusion MX), I can display the total of these percentages. The total of all the percentages needs to add up to 100%. This is all done using only ColdFusion.

On the form, users can change the value of the any of the numbers/percentages. I have an onChange as part of the text box that, when the value is changed, the form will submit and write to the database to give the new total.

What I would like to do is have a “real-time” total that displays the added values of all the percentages without having to submit the form. I’m sure this is possible using Javascript but I’m not sure how. Can anyone point me to an example or give me some advice? The number of rows can/do vary so I can’t “hardcode” something like Total = Textbox1 + Textbox2, etc…

Any advice/help is greatly appreciated!


10-02-2006, 10:24 PM
The number of rows is dynamic?

Well, I suppose you could do it with a for loop.
Title each consecutively created textbox "textbox1", "textbox2", etc. where the important part is the number.
In the for loop, add one to the n variable, and check if the textbox exists.
Add the value of that textbox (textbox.value) to another variable, then when you reach the end of the loop (place after the loop in the script), divide the total by the n variable for how many textboxes there are.
I'm not sure exactly how to do this, but from a general programming viewpoint, that makes total sense. I think it should work in javascript.
If you can't check if an element exists directly, then you could check if textbox.value != "", so... it's not an empty string, so therefore, it has a value.

The other way would be the inverse-- going from the textboxes to the output.
You could have an onChange component on the textbox itself and basically have it add it's value to the total variable, then change the output of the total variable at the top of the page or wherever.
However, the problem there is that you would need to keep track of which textboxes have been added to know how many to divide by and account for changes, where you would subtract the previous value and add the new value.

I think the first option makes the most sense...