...

View Full Version : What is wrong with this?



hendryk
07-25-2002, 05:42 PM
Hi,

The array contains the field names in the form - I will be adding more of these if I can get it to work!

If these fields are blank I want it to display an error message if not I want the form to be submitted. As it is, the form is submitted when these fields are blank (not good!)

Can someone fix it?





function validateFields (aform)
{ var fieldArray = ["hospUnitNo","paedSurgeon1"];
var field = "";
var decision = true;
var prompt = "";
var i = 0;
for (i = 0; i<fieldArray.length;i++)
{
field = fieldArray[i];
if(field.value =="")
{
decision = false;
break;
}
}

if (!decision){alert(field + " is a required field. Please enter a value.");}
else { aform.submit(); prompt = "The form is being submitted.";alert(prompt);}

}

head8k
07-25-2002, 06:08 PM
I haven' t got time to fix it because I'm half way out the door at work.:) You will need to look into using the eval() method inside your for loop. Do a search and you should get some pointers. If you're still stuck tomorrow I'll write you a fix.

ShriekForth
07-25-2002, 06:32 PM
Two things, head8k was right, you will need to use eval on the function, like so.

field = eval("aform."+fieldArray[i]);

this will give you the formreference you need, but you will show [object] when you try to display it in the error message, so before you break, I would place the form name into a string.


for (i = 0; i<fieldArray.length;i++){
field = eval("aform."+fieldArray[i]);
if(field.value ==""){
fieldName = fieldArray[i];
decision = false;
break;
}
}
if (!decision){alert(fieldName + " is a required field. Please enter a value.");}
else { aform.submit(); prompt = "The form is being submitted.";alert(prompt);}


The form name might not be too useful to the user though. You could have a seccond array, or a multidimentional array set up with a better display name.

ShriekForth

boywonder
07-26-2002, 12:23 AM
Assuming you are already passing the form's reference to the function, you already have an array of the form elements built in. Below will verify that none of the text boxes in your form are empty. Advantage is there's no need to list the text fields within your function and it doesn't matter how many you have or if you add more or remove some.

<script>
function validateFields (aform) {
var i, curr;
for(i=0;i<aform.length;i++){
curr = aform[i];
if (curr.type!="text") continue;
if(curr.value=="") {
alert(curr.name + " is a required field. Please enter a value.");
return false;
}
}
return true;
}
</script>

hope that helps you.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum