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.
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=="text" && form.elements.name!="total" {
[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 != "" {
[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="text" onChange="this.form.total.value=calculate(this.form);">
enter a number: <input type="text" onChange="this.form.total.value=calculate(this.form);">
enter a number: <input type="text" onChange="this.form.total.value=calculate(this.form);">
total: <input type="text" name="total"><input type="button" value="Calculate!" onClick="calculate(this.form);">
</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.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.