I am writing a validation script for an HTML form. The script makes a list of errors appear at the top of the document, so that the user can see (and correct) them all at once. I’d like the focus to move to that error list when the document reloads after the validation script runs, but this isn’t working, and heaven help me I can’t see why. Any tips would be very much appreciated. Thank you!
Here is the JS
function validate(survey) {
var error=document.createElement("text");
error.innerHTML=" ";
var x=document.survey.member_email.value;
if (x==null || x=="") {
error.innerHTML+="<li>Please enter an email address</li>"
var vp=document.getElementById("validate_place");
vp.appendChild(error);
vp.focus( ); // Here is the focus command -->//
return false;
}
return true;
}
And here are the validation lines in HTML:
<form action="survey_processing.php" method="post" onsubmit="return validate(this);" name="survey" id="survey" >
<div id="validate_place" > </div> <!--- empty div to insert validation correction info if needed -->
By setting the
tabindexattribute of the div to -1 you enable the ability to pass focus to it programatically. (scroll down to tabindex at the MDN article for more details)