Java Reference
In-Depth Information
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 select() method. This makes
it even clearer to the users what they need to fix. It also allows them to rectify the problem without
needing to delete text first.
if (isNaN(target.value)) {
alert("Please enter a valid age");
target.focus();
target.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 handles the blur event of the txtAge text box, but why didn't you use the change event,
with its advantage that it only rechecks the value when the value has actually been changed? The
change event would not fire 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 fill in information out of order and
come back to some form elements later.
The final function is for the txtName text box's change event. Its use here is a little flippant and
intended primarily as an example of the change event:
function txtNameChange(e) {
alert("Hi " + e.target.value);
}
When the change event fires (when focus is passed away from the name text box and its contents have
changed), you take the value of the event target (again, making use of the target property) and put it
into an alert box. It simply says Hi yourname .
problems with Firefox and the blur event
The previous example will fail with Firefox if you enter a name in the name text box and then an
invalid age into the age box (for example, if you enter abc and then click the Check Form button).
With other browsers the blur event fires and displays an alert box if the age is invalid, but the
button's click event doesn't fire. However, in Firefox, both events fire with the result that the
invalid age alert is hidden by the “form completed successfully” alert box.
In addition, if you enter an invalid age and then switch to a different program altogether, the
“invalid age” alert box appears, which is annoying for the user. It could be that the user was
opening up another program to check the details.
Although this is a fine example, it is not great for the real world. A better option would be to check
the form when it's finally submitted and not while the user is entering data. Or, alternatively, you
can check the data as it is entered but not use an alert box to display errors. Instead you could
 
Search WWH ::




Custom Search