javascript thread: I need some help.
Karla ---
Just convert the empty string into a 0 by testing for an empty string or
isNan (is Not a Number). In addition, use the radix value 10 with parseInt
so as to avoid any conversion of the number into hexadecimal (in the event
your user enters something like 08 or 09 for the value).
function button1_onclick()
{
var value1=document.form1.text1.value;
var value2=document.form1.text2.value;
var value3=document.form1.text3.value;
if (value1 == "" || isNan(value1)) {
value1 = 0;
} else {
value1 = parseInt(value1, 10);
}
if (value2 == "" || isNan(value2)) {
value2 = 0;
} else {
value2 = parseInt(value2, 10);
}
if (value3 == "" || isNan(value3)) {
value3 = 0;
} else {
value3 = parseInt(value3, 10);
}
document.form1.text4.value=value1+value2+value3;
}
You could also take the if statement that checks the value and create a
function with it so as to avoid having it written three times within this
function.
Michael
----- Original Message -----
From: "Karla De Uslar" <ttmcguir@s...>
To: "javascript" <javascript@p...>
Sent: Friday, May 25, 2001 11:12 AM
Subject: [javascript] I need some help.
> Hi, I'm new to javascript so please forgive me if this question seems very
> simple. I'm trying to add numerical values from 3 text boxes with their
> sum displaying in the 4th text box. The code works fine when each of
> the 3 "addition" text boxes has a number entered into it. The problem
> arises when one of the 3 "addition" text boxes is left empty, the sum that
> is returned in the 4th text box is....NaN..... Is there a way to rewrite
> the following code to allow for one or more of the "3 addition" text boxes
> to remain empty? Here is my code.
>
> <!--
> function button1_onclick()
> {
> var value1=parseInt(document.form1.text1.value);
> var value2=parseInt(document.form1.text2.value);
> var value3=parseInt(document.form1.text3.value);
>
> document.form1.text4.value=value1+value2+value3;
> }
> //-->
>
> Thank you for your help.
>
>