Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1472 When submitting a form with multiple fields to a validation function, and if there's an invalid entry in one of the fields, how do you return focus to that field and reset only the value of that field, and not the rest of the form?

You are here: irt.org | FAQ | JavaScript | Form | Q1472 [ previous next ]

Try:

<script language="JavaScript"><!--
function validate(theForm) {
   errorField = -1;
   for (i=0,n=theForm.elements.length;i<n;i++) {
      if (theForm.elements[i].value == '') {
         errorField = i;
         break;
      }
   }
   if (errorField !=-1) {
      alert('Please correct field number ' errorField+1);
      theForm.elements[i].focus();
      return false;
  }
  return true;
}
//--></script>
<form onSubmit="return validate(this)">
...
</form>

Feedback on 'Q1472 When submitting a form with multiple fields to a validation function, and if there's an invalid entry in one of the fields, how do you return focus to that field and reset only the value of that field, and not the rest of the form?'

©2018 Martin Webb