Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

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?

irt.org | Knowledge Base | JavaScript | Form | Q1472 [ previous next ]

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?

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?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.