Setting the focus
Note: The following example may not
work on Microsoft Internet Explorer 3.x. You will find that the focus is
not set properly. If anyone figures out what the problem actually is, please
let me know.
In the preceeding example, the message gave no clue as to which field is
actually causing problems. Usually forms are much bigger and such a message
will not be of much use. In the next form, not only is the message more
informative, but the cursor is also placed at the erring field so that
the user can start typing in directly. For example, to position the cursor
in the first field (yourname), we can use the JavaScript function
document.sample.yourname.focus(). Here is the modified function.
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide code from non-js browsers
function validateForm()
{
formObj = document.sample;
if (formObj.yourname.value == "")
{
alert("You have not filled in the name field.");
formObj.yourname.focus();
return false;
}
else if (formObj.yourage.value == "")
{
alert("You have not filled in the age field.");
formObj.yourage.focus();
return false;
}
else if (formObj.yourdob.value == "")
{
alert("You have not filled in your date of birth.");
formObj.yourdob.focus();
return false;
}
}
// end hiding -->
</SCRIPT>
Here is our new form.