Java Reference
In-Depth Information
The next of the three functions is txtAge_onblur(), which connects to the onblur 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 number characters.
function txtAge_onblur()
{
var txtAge = document.form1.txtAge;
Again at the start of the function, you declare a variable and set it to reference an object; this time it's the
Text object created for the txtAge text box that you defi ne further down the page. Now, instead of having
to type document.form1.txtAge every time, you just type txtAge , and it does the same thing. It certainly
helps save those typing fi ngers, especially since it's a function with multiple use of the txtAge object.
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
text box is not a number, it tells the user and sets the focus back to the text box by calling the focus()
method. Additionally, this time you highlight the text by using the Text object's select() method.
This makes it even clearer to the user what they need to fi x. It also allows them to rectify the problem
without needing to delete text fi rst.
if (isNaN(txtAge.value) == true)
{
alert(“Please enter a valid age”);
txtAge.focus();
txtAge.select();
}
}
You could go further and check that the number inside the text box is actually a valid age — for example,
191 is not a valid age, nor is 255 likely to be. You just need to add another if statement to check for these
possibilities.
This function is connected to the onblur event handler of the txtAge text box, but why didn't you
use the onchange event handler, with its advantage that it only rechecks the value when the value has
actually been changed? The onchange event would not fi re if the box was empty both before focus
was passed to it and after focus was passed away from it. However, leaving the checking of the form
completion until just before the form is submitted is probably best because some users prefer to fi ll in
information out of order and come back to some form elements later.
The fi nal function is for the txtName text box's onchange event. Its use here is a little fl ippant and
intended primarily as an example of the onchange event.
function txtName_onchange()
{
window.status = “Hi “ + document.form1.txtName.value;
}
When the onchange event fi res (when focus is passed away from the name text box and its contents
have changed), you take the value of the txtName box and put it into the window's status bar at the
bottom of the window. It simply says Hi yourname. You access the status bar using the window object's
status property, although you could just enter the following:
status = “Hi “ + document.form1.txtName.value;
Search WWH ::




Custom Search