Forum Moderators: open

Message Too Old, No Replies

For Loop & Form Validation

         

lbombardier

10:23 pm on Dec 11, 2008 (gmt 0)

10+ Year Member



I just cannot get the following code to work! Driving me crazy. If remove the loop and just evaluate "reason = validateEmpty(theForm.name)" it works fine. The idea is I want to use a loop so I can just to the array rather than have multiple "reason = validate..." entries.

I get the error that "theForm.items" is not defined.

Help?!

function validateFormOnSubmit(theForm) {

var reason = "";

// Check for empty fields

var items=["name", "company"];

for (var i = 0; i < items.length; i++) {
reason = validateEmpty(theForm.items[i]);
}
if (reason != "")
{
alert(reason);
return false;
}
return true;
}

function validateEmpty(fld) {
var error = "";

if (fld.value.length == 0) {
fld.style.border = "2px solid #FF0000";
error = "Some required fields are empty.\n"
} else {
fld.style.background = 'White';
}
return error;
}

astupidname

1:27 am on Dec 12, 2008 (gmt 0)

10+ Year Member



Just a suggestion, have you tried something like this:

for (var i = 0; i < items.length; i++) {
var a = items[i];
reason = validateEmpty(theForm[a]); //or try theForm.a
}

daveVk

3:21 am on Dec 12, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



theForm.elements instead of theForm.items ?