Creating A Form
The following is a form with three fields, a submit
button and a reset button.
The above form was created using HTML code similar to
the following :
<FORM NAME="sample" METHOD=POST ACTION="/scripts/youraction.exe">
Enter your name : <INPUT TYPE=TEXT NAME="yourname" SIZE=30><BR>
Enter your age : <INPUT TYPE=TEXT NAME="yourage" SIZE=3><BR>
Date of birth : <INPUT TYPE=TEXT NAME="yourdob" SIZE=10><BR>
<INPUT TYPE=SUBMIT> <INPUT TYPE=RESET>
</FORM>
We can refer to this form as document.sample
.
The first text field is document.sample.yourname
and the second field is document.sample.yourage
.
To get the text which is entered in the first text
field, you can use document.sample.yourname.value
. Now let us see how to go about validating the
data entered.
Setting the focus
Note: The
following example may not work on Microsoft Internet
Explorer 3.0. You will find that the focus is not set
properly. I think the problem occurs only if you have
installed the patch but I am not sure about this.
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.