August 5, 2000 - Preparing a Form for User Corrections
August 5, 2000 Preparing a Form for User Corrections Tips: August 2000
Yehuda Shiran, Ph.D.
|
text
object is the select()
method. When you select a field via JavaScript, the entire text in the field is selected. Due to a bug in Internet Explorer, you must first give a focus and then a blur to a text field, before selecting it. Such a sequence looks like this:
document.forms[0].elements[0].focus();
document.forms[0].elements[0].blur();
document.forms[0].elements[0].select();
The select()
method is extremely useful and very convenient when validating a form. Let's say you have a form which accepts inputs from the user for several elements, and validates each element in turn, before submitting the data to the server. The most basic way to report an error is to display a message in a dialog box. More sophisticated error reporting consists of automatic preparation of the form for the user's corrections. Such preparation can be implemented by playing the focus()
+ blur()
+ select()
method concert. When the script encounters a text field that contains invalid data, you can direct the cursor to that field and automatically select the interior text. The user can then write the new, corrected value without even having to delete the invalid entry. Try playing around with the following fields. The name field should have a space and the e-mail field should include the @ sign:
Here is the script:
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkName(field) {
if (field.value == "") {
alert("Value is required");
field.focus();
field.blur();
field.select();
}
else {
if (field.value.split(" ").length < 2) {
alert("Enter a full name");
field.focus();
field.blur();
field.select();
}
}
}
function checkEmail(field) {
if (field.value.indexOf("@") == -1) {
alert("Enter a valid e-mail address");
field.focus();
field.blur();
field.select();
}
}
// -->
</SCRIPT>
<FORM>
Full Name: <INPUT TYPE="text" NAME="userName" VALUE="" SIZE="15" onChange="checkName(this)">
Email address: <INPUT TYPE="text" NAME="email" VALUE="" SIZE="15" onChange="checkEmail(this)">
</FORM>