
Originally Posted by
NXArmada
Im trying to get 3 of my fields to multiply ex: A+B*C = D
and 2 of my fields to add ex: D+E=F
Care to describe the problem you're having? You've avoided the common problem of trying to add strings (which will result in concatenation, not arithmetic addition), though there are still some issues.
First, when working with forms and form controls, it's usually best to pass a reference to the element in question. This is especially true if a function can be reused.
In intrinsic event attributes, the this operator will refer to element. For example, in:
HTML Code:
<form action="..." onsubmit="return validate(this);">
the validate function will be called when the form is submitted, and its first argument will be a reference to that form.
A = document.edit.tax.value
B = document.edit.scost.value
There are three issues, here. One is stylistic.
- Variables, including globals, should always be declared, and given as little scope as possible.
- In my opinion, and undoubtedly other's, adding form elements and form controls as properties of the document and form objects, respectively, was a bad idea. It's sloppy and leads to naming conflicts. There are already two collections - forms and elements - for that purpose. Use these, instead.
- I suggest using descriptive names for your variables. It's also good form to terminate statements with semicolons.
A = Number(A)
B = Number(B)
Though the Number constructor function can be used to type-convert values and objects to numbers, the unary plus (+) operator is much simpler and more efficient.
The result looks something like:
Code:
function total(form) {
var elements = form.elements,
subtotal = +elements.scost.value,
tax = +elements.tax.value;
elements.tcost.value = subtotal + tax;
}
I assume that the 's' in 'scost' stands for sub-total (or a synonym).
Note that if values are entered by the user, though presumably these particular values aren't, you should validate the input before acting on it.
The tax function would undergo a similar change.
We will, as soon as you tell us what the problem is. 
Mike
Bookmarks