addition

M

magix

I have following function, but how can I do addition ?
if
f.Field1.value =2
f.Field3.value =3
f.Field4.value =1

then
f.Total.value =231, instead of 6


function update( ) {
var f = document.myform
f.Total.value = f.Field1.value + f.Field2.value + f.Field3.value
return true;
}

Many thanks.
 
S

scripts.contact

I have following function, but how can I do addition ?
function update( ) {
var f = document.myform
f.Total.value = f.Field1.value + f.Field2.value + f.Field3.value
return true;
}

function update( ) {
var f = document.forms['myform'] //- this part is not important
f.Total.value = +f.Field1.value + +f.Field2.value + +f.Field3.value
return true;

}
 
T

Tim Slattery

magix said:
I have following function, but how can I do addition ?
if
f.Field1.value =2
f.Field3.value =3
f.Field4.value =1

parseInt(f.Field1.value) + parseInt(f.Field3.value) +
parseInt(f.Field4.value)
 
R

RobG

I have following function, but how can I do addition ?
if
f.Field1.value =2
f.Field3.value =3
f.Field4.value =1

then
f.Total.value =231, instead of 6

function update( ) {
var f = document.myform
f.Total.value = f.Field1.value + f.Field2.value + f.Field3.value
return true;

}

The values returned by form controls are strings, they must be
converted to numbers or the '+' operator will cause concatenation, not
addition:

<URL: http://www.jibbering.com/faq/#FAQ4_21 >
 
D

Dr J R Stockton

In comp.lang.javascript message <2hlgv2l2ggbg5cdpv9mdp4h4cukpoofada@4ax.
parseInt(f.Field1.value) + parseInt(f.Field3.value) +
parseInt(f.Field4.value)

parseInt should only be used without a second parameter under specific
conditions.

For a good answer, quoting FAQ 4.21 is necessary and should be
sufficient.

For multiple fields, consider
- ( -f.Field1.value -f.Field2.value -f.Field3.value )

Or write a function FV(g) { return +g.value } and use it as
FV(f.Field1) + FV(f.Field2) + FV(f.Field3)



It's a good idea to read the newsgroup and its FAQ. See below.
 
E

Evertjan.

Dr J R Stockton wrote on 15 mrt 2007 in comp.lang.javascript:
For a good answer, quoting FAQ 4.21 is necessary and should be
sufficient.

For multiple fields, consider
- ( -f.Field1.value -f.Field2.value -f.Field3.value )

Or write a function FV(g) { return +g.value } and use it as
FV(f.Field1) + FV(f.Field2) + FV(f.Field3)

A moe general solution:

function sumOfFields(begin,end,frm,elem){
var r = 0;
for (var i=begin; i<=end; i++)
r -= frm.elements[elem+i].value;
return -r;
]

result = sumOfFields(1,3,f,'Field')
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top