PDA

View Full Version : JavaScript - logical error in for loop?



web88js
05 May 2007, 01:31 PM
hello everyone:

I am trying to use a for loop iterate through elements on a form.
inside the for loop I have a switch statement which validate each individual fiels. the test expression is based on the name of the field.

my problem is that when user left name field blank(one of the error case).
it won't exit for loop and kept prompting second condidtion in switch statement then goes into checkAge() function.

I think the cause might be a logical error in my code, but I could not find out what's the error is, please help me to identify the error and how to solve the problem. Thanks for your help.

Here is my sample code (http://www.cuj06.com/js_project/multi_fieldValidation.html)

here is my checkAge function


function checkAge(elementReference)
{
var ageStr = elementReference.value;
alert("vlue of ageStr is " + ageStr.value); //debug message
alert("length of the string is " + ageStr.length); //debug message
var temp;
var age="";
var number_count = 0;
var strAge="";

//use for loop to go through the string get from name text field
for(i = 0; i < ageStr.length; i++)
{
temp = ageStr.charAt(i);
if(!isNaN(temp)) //filter out character data in string keep the digits
{
age +=temp;
number_count++;
}
else
{
strAge += temp; //concatenate all characters in the string to strAge
}

}

//parse string into integer use Number function;
var intAge = Number(age);
alert ("intAge is " + intAge);//debug message
alert ("strAge is " + strAge);//debug message

//test to see if age field left blank
if(ageStr.value == undefined)
{
alert("age field is blank, please fill out the age field");
return false;
}

//cases to handle user's entry is characters only
else if(number_count == 0 && ageStr.length == 1)
{
alert( strAge + " is an invalid entry. Please enter a number");
return false;
}

else if(number_count == 0 && ageStr.length == 2)
{
alert( strAge + " is an invalid entry. Please enter a number");
return false;
}

else if(number_count == 0 && ageStr.length == 3)
{
alert( strAge + " is an invalid entry. Please enter a number");
return false;
}

//test number entered by user is between 10 and 99
//when age field is left blank intAge became 0,
else if(intAge < 10 || intAge > 99)
{
alert ("please enter an age between 10 and 99");
return false;
}
else
return true;

}//end of function age_check