Simple form validation problem

Hi,

I am checking a subset of compulsory fields to avoid them from remaining empty.

My form:

<form action=“quote.php” method=“post” name=jquoteform id=jquoteform onSubmit=“return valid(this)”>
<label>Last name*:<span class=red> </span></label>
<input id=“jQuoteLastname” name=“jQuoteLastname” class=“quoteField” type=“text”><br />
<label>First name
:<span class=red> *</span></label>
<input id=“jQuoteFirstname” name=“jQuoteFirstname” class=“quoteField” type=“text”><br />
</form>

Initially I would use this script:

function valid(form) {
  if (form.jQuoteLastname.value=='') {
    form.jQuoteLastname.style.backgroundColor='red';
    return false;
  }
  else { form.jQuoteLastname.style.backgroundColor=''; }  

  if (form.jQuoteFirstname.value=='') {
    form.jQuoteFirstname.style.backgroundColor='red';
    return false;
  }
  else { form.jQuoteFirstname.style.backgroundColor=''; }

  return true;
}

Now for big form I want to have an array of filed names and use a loop instead of repeating the code. But my code forwards to the result form just after checking first field and strangely does not do anything:

function valid(form) {
  var x;
  var myFields=["employAppSex","employAppPrimaryEmail","employAppTranslatorStatus","employAppFullAddress"]; 

  for (x in myFields)
  {
        if (form.getElementsById(myFields[x]).value=='') 
        {
            form.getElementsById(myFields[x]).style.backgroundColor='red';
            return false;
        }
        else { form.myFields[x].style.backgroundColor=''; }  
  }

  return true;
}

Even the follwoing code does not iterate over all the fields and just alerts the name of the first field and not even its value. and then immediately forwards to the resulting page (even if I leave the form empty).

function valid(form) {
  var x;
  var myFields=["employAppSex","employAppPrimaryEmail","employAppTranslatorStatus"]; 

  for (x in myFields)
  {
        alert("iterating on:"+ myFields[x]);
        alert("value: "+form.getElementsById(myFields[x]).value)
  }

  return false; //intentionally made false
}

What is the problem?

I am struggling with this for a few hours :slight_smile: without success. I’ll appreciate if someone can help.

thanks

For future reference, it is getElementById, not getElementsById

And I’m pretty sure it only works on document, thus document.getElementById. form.getElementById may also work but I’m not sure, form.getElementsById certainly won’t work :slight_smile:

Problem is finally solved.

I needed to use

form.elements[myFields[i]]

instead of

form.getElementsById(myFields)

Thanks.