Java Reference
In-Depth Information
These are convenience variables, thus reducing the size of your code (you don't have to type
myForm
.txtName
every time you reference the
txtName
object). It makes your code more readable and
therefore easier to debug, and it saves typing.
After getting the reference to the
<input/>
element objects, 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 (txtAge.value == "" || txtName.value == "") {
alert("Please complete all of the form");
if (txtName.value == "") {
txtName.focus();
} else {
txtAge.focus();
}
}
If you do find an incomplete form, you alert the user. Then in an inner
if
statement, you check which
text box was not filled in. You set the focus to the offending text box, so that the user can start filling 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 fill in. To avoid annoying your users, make sure that text in the page tells
them which fields are required.
If the original outer
if
statement finds that the form is complete, it lets the user know with a thank‐you
message:
else {
alert("Thanks for completing the form " + txtName.value);
}
}
In this sort of situation, it's probably more likely that you'll 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.
The next of the three functions is
txtAgeBlur()
, which handles the
blur
event of the
txtAge
text
box. This function's purpose is to check that the string value the user entered into the age box actually
consists of numeric characters:
function txtAgeBlur(e) {
var target = e.target;
At the start of the function, you retrieve the target of the event (the
txtAge
text box) and store it in the
target
variable. You could use
myForm.txtAge
to reference the same
txtAge
text box, but using the
Event
object's
target
property is a better solution. The
txtAgeBlur()
function works only with the
element that received the
blur
event. As such, using the
Event
object's
target
property gives you a
generalized function that doesn't depend on any external variables, such as
myForm
. Plus, it's less typing.
The following
if
statement checks to see whether what has been entered in the
txtAge
text box can
be converted to a number. You use the
isNaN()
function to do this for you. If the value in the
txtAge