August 5, 2000 - Preparing a Form for User Corrections | WebReference

August 5, 2000 - Preparing a Form for User Corrections

Yehuda Shiran August 5, 2000
Preparing a Form for User Corrections
Tips: August 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

The most useful method of the 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:


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:

Full Name: Email address:
Here is the script:

function checkName(field) {
  if (field.value == "") {
    alert("Value is required");
  else {
    if (field.value.split(" ").length < 2) {
	  alert("Enter a full name");
function checkEmail(field) {
  if (field.value.indexOf("@") == -1) {
    alert("Enter a valid e-mail address");
// -->
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)">