Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding numbers from a text object value?

Status
Not open for further replies.

hd65

Technical User
Aug 17, 2000
27
US
I have several text boxs that display a number (subtotal)and I need to add all the (subtotals) and display that number in another textbox. Is this close??
form.text1box.value = form.text2box.value + form.text3box.value....I know it's not right I get NaN error.
 
here's a function to do what you want:

function calculate(form)
{
[tab]var i;
[tab]var res=0;

[tab]// Loop through everything in the form
[tab]for (i=0;i<form.length;++i) {
[tab][tab]// only look at text elements and ignore total field
[tab][tab]if (form.elements.type==&quot;text&quot; && form.elements.name!=&quot;total&quot;) {
[tab][tab][tab]// skip entries that are empty or don't contain a number
[tab][tab][tab]if (!isNaN(form.elements.value) && form.elements.value != &quot;&quot;) {
[tab][tab][tab][tab]res+=eval(form.elements.value);
[tab][tab][tab]}
[tab][tab]}
[tab]}
[tab]return(res);
}

Here's some sample HTML to use it:

<form>
enter a number: <input type=&quot;text&quot; onChange=&quot;this.form.total.value=calculate(this.form);&quot;>
enter a number: <input type=&quot;text&quot; onChange=&quot;this.form.total.value=calculate(this.form);&quot;>
enter a number: <input type=&quot;text&quot; onChange=&quot;this.form.total.value=calculate(this.form);&quot;>
total: <input type=&quot;text&quot; name=&quot;total&quot;><input type=&quot;button&quot; value=&quot;Calculate!&quot; onClick=&quot;calculate(this.form);&quot;>
</form>

Instead of having the script just skip entries that are blank or don't contain a number, you'll want to require (within the constraints of javascript) the user, to fill in an acceptable value. Also, you can implement the calculation method in a number of ways. You could remove all the onChange events and just have them click a button. Or add onFocus, onBlur events etc. Make sure that your total field name matches the condition above in the calculate function.

I haven't tested this in Netscape browsers. It's been awhile since I've written anything in javascript and for some reason, the type property of form.elements seems suspect.

Hope this helped!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top