...

View Full Version : adding text boxes



blkskull
12-13-2006, 08:42 PM
I'm doing a school project and I'm trying to add up several text boxes, however some of them are blank and when I calculate them I get a NaN result. Here is my code:

qty1= parseFloat(document.form1.qty_prt.value)
qty2= parseFloat(document.form1.qty_mon.value)
qty3= parseFloat(document.form1.qty_comp.value)
sub_tot=parseFloat(document.form1.subt.value)
tax_tot=parseFloat(document.form1.tax.value)
grand_tot=parseFloat(document.form1.grandt.value)
qty_tot=eval(qty1+qty2+qty3)
alert("quantity is " + qty_tot)

nikkiH
12-13-2006, 10:10 PM
isNaN() is a function provided for just such things.
http://www.devguru.com/Technologies/ecmascript/quickref/isnan.html

Not sure if there is a better way, but I'd just test each one first.
e.g.
qty1= isNaN(parseFloat(document.form1.qty_prt.value))?0:document.form1.qty_prt.value

You don't need eval. Eval is Evil. :D
qty_tot=qty1+qty2+qty3

blkskull
12-14-2006, 04:29 PM
Okay I get what you're doing in the forst part qty1= isNaN(parseFloat(document.form1.qty_prt.value)) your converting the value if any to numeric value and checking if it is numeric(I think).
However what is the second part ?0:document.form1.qty_prt.value?

nikkiH
12-14-2006, 07:55 PM
That's shortcut syntax for an if/then when doing an assignment.

i.e.

int c = 0;
if (b == 1)
{
c = 2;
}
else
{
c = 5;
}

Can be written as
int c = b==1 ? 2 : 5;

So this (note the 2nd parseFloat i forgot, actually):

qty1= isNaN(parseFloat(document.form1.qty_prt.value))?0:parseFloat(document.form1.qty_prt.value);

is a shortcut for this:

if (isNaN(parseFloat(document.form1.qty_prt.value)))
{
qty1 = 0;
}
else
{
qty1 = parseFloat(document.form1.qty_prt.value)
}

blkskull
12-15-2006, 02:53 PM
Thanks for the explaination, I'll give it a try.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum