Java Reference
In-Depth Information
The fi rst text box's onchange event handler is connected to the function txtName_onchange(), the
second text box's onblur event handler is connected to the function txtAge_onblur(), and the but-
ton's onclick event handler is connected to the function btnCheckForm_onclick(). These functions
are defi ned in a script block in the head of the page. You will look at each of them in turn, starting with
btnCheckForm_onclick().
The fi rst thing you do is defi ne a variable, myForm , and set it to reference the Form object created by the
<form/> element later in the page.
function btnCheckForm_onclick()
{
var myForm = document.form1;
Doing this reduces the size of your code each time you want to use the form1 object. Instead of
document.form1, you can just type myForm. It makes your code a bit more readable and therefore easier
to debug, and it saves typing. When you set a variable to be equal to an existing object, you don't (in
this case) actually create a new form1 object; instead you just point your variable to the existing form1
object. So when you type myForm.name, JavaScript checks your variable, fi nds it's actually storing the
location in memory of the object form1, and uses that object instead. All this goes on behind the scenes
so you don't need to worry about it and can just use myForm as if it were document.form1.
After getting the reference to the Form object, you then use it in an if statement to check whether the
value in the text box named txtAge or the text box named txtName actually contains any text.
if (myForm.txtAge.value == “” || myForm.txtName.value == “”)
{
alert(“Please complete all the form”);
if (myForm.txtName.value == “”)
{
myForm.txtName.focus();
}
else
{
myForm.txtAge.focus();
}
}
If you do fi nd an incomplete form, you alert the user. Then in an inner if statement, you check which
text box was not fi lled in. You set the focus to the offending text box, so that the user can start fi lling it
in straightaway without having to move the focus to it herself. It also lets the user know which text box
your program requires her to fi ll in. To avoid annoying your users, make sure that text in the page tells
them which fi elds are required.
If the original outer if statement fi nds that the form is complete, it lets the user know with a thank-you
message.
else
{
alert(“Thanks for completing the form “ + myForm.txtName.value);
}
}
In this sort of situation, it's probably more likely to submit the form to the server than to let the user
know with a thank-you message. You can do this using the Form object's submit() method or using a
normal Submit button.
Search WWH ::




Custom Search