Приглашаем посетить
Блок (blok.lit-info.ru)

Programming Text Input Elements

Programming Text Input Elements

HTML supports the following four types of text controls for requesting input from the user:

The TEXT Input element creates a single-line text box, and the Textarea element creates a multiple-line text box. The PASSWORD Input element is a special single-line text box in which the user's input is visually masked on the screen—each character the user types is displayed as an asterisk (*). The FILE Input element displays a text box and button with which the user can select a local file. When the form is submitted, the contents of the selected file are sent back to the server.


NOTE: The TextArea element, as with any element that displays scrollbars in Dynamic HTML, exposes scrollTop, scrollLeft, scrollWidth, and scrollHeight properties. These properties provide full access to the size of the contents and the extent of the contents currently being viewed. For more information about these four properties, see Chapter 9, "Scripting Individual Elements."

The various text Input elements in HTML currently do not have built-in functionality for validating and formatting user input. Prior to scripting, such functionality had to be performed on the server, often creating unnecessary round-trips. By writing client-side scripts and using Dynamic HTML, you can format and validate input instantly on the client. This section focuses on techniques for testing user input.

Accessing the Control's Contents

The contents of the text Input elements are exposed through two techniques: the value or innerText property for direct access to the contents as a string, and the createTextRange method for rich access to the contents as characters, words, or sentences. The innerText property is an alias for the value property; the two can be used interchangeably. Text manipulation using the TextRange object is discussed in Chapter 14, "User Selection and Editing Operations." This chapter focuses on using the value property for manipulating the contents of the control.

The File Upload Element

The <INPUT TYPE=FILE> tag allows the contents of the file specified in the text box to be uploaded to the server. For security reasons, the File Upload element has a limited object model. The File Upload element is supported by Netscape Navigator 3.0 and later and by Internet Explorer 3.02 and later. Its value property is read-only and represents the filename and path, not the file's contents. Events are supported on the File Upload element, but their use is fairly limited since you cannot manipulate the user's input. When required, you can use the events and the value property to check that a file is selected.

Validating User Input

Validating user input prior to processing improves the usability of your Web site. This section presents four techniques that can be used with any text input from the user.

Validating While the User Types

Validation can be performed on each character the user types by tracking keyboard events: keypress, keydown, and keyup. The keypress event is the best event to use for tracking keyboard input because the default action of the keypress event is to process the typed character. Returning a value of false to this event prevents the character from being processed, so the character won't be appended to the user input. The following example demonstrates how to limit a text box to numeric input.

<HTML>
   <HEAD>
      <TITLE>Validating While the User Types</TITLE>
   </HEAD>
   <BODY>
      <LABEL FOR="age">Age</LABEL>
      <INPUT ID="age" TYPE=TEXT SIZE=3
         ONKEYPRESS="if ((event.keyCode < 48) ||
            (event.keyCode > 57)) event.returnValue = false;">
   </BODY>
</HTML>

This text box allows only ASCII values from 48 to 57, which represents the numerals 0 through 9 on the keyboard. Any other character typed by the user is ignored.

Validating When the User Exits the Control

Immediate validation is most useful for filtering user input. A more common approach is to validate the input at the time the user completes entering a new value. When an invalid value is entered, the user should be notified using at least one of the following two techniques:

Both techniques take advantage of the onchange event, which is fired at the time the user exits an input control after changing the value. The onchange event is fired on the element immediately prior to the onblur event. It can be used to validate the user's entry and then to display a dialog box or change the form's appearance based on the entry. Canceling the onchange event prevents the user from exiting the control when navigating within the page. If the user is navigating to a new page, canceling this event does not stop the navigation.

The following code demonstrates changing the style of an element based on the entered value. This technique is described in detail in Chapter 11, "Dynamic Styles." Dynamically changing the style is useful for providing the user with clear feedback.

<HTML>
   <HEAD>
      <TITLE>Validating When Exiting a Control--Technique 1</TITLE>
      <STYLE TYPE="text/css">
         .badValue {background:red; color:white}
      </STYLE>
      <SCRIPT LANGUAGE="JavaScript">
         function validateNumber() {
            // Get the source element.
            var el = event.srcElement;
            // Valid numbers
            var num = "0123456789";
            event.returnValue = true;
            /* Loop over contents. If any character is not a number,
               set the return value to false. */
            for (var intLoop = 0; 
               intLoop < el.value.length; intLoop++)
               if (-1 == num.indexOf(el.value.charAt(intLoop))) 
                  event.returnValue=false;
            if (!event.returnValue)       // Bad value
               el.className = "badValue"; // Change class.
            else
               // Clear class to use default rendering.
               el.className="";
         }
      </SCRIPT>
   </HEAD>
   <BODY>
      <LABEL FOR="Age">Age:</LABEL>
      <INPUT ID="Age" TYPE=TEXT SIZE=3 TITLE="Enter your age"
         ONCHANGE="validateNumber();">
   </BODY>
</HTML>

Instead of changing the style of the element, you can warn the user with an Alert dialog box when an invalid value is entered. The following code demonstrates how to alert the user if he or she enters an invalid value in a State field. In addition, this code performs rudimentary formatting by making the user's input uppercase.

<HTML>
   <HEAD>
      <TITLE>Validating When Exiting a Control--Technique 2</TITLE>
      <SCRIPT LANGUAGE="JavaScript">
         function checkState(check) {
            var states = "ALAKAZARCACOCTDEDCFLGAHIIDILINIAKS";
            states += "KYLAMEMDMAMIMSMNMOMTNENMNVNHNJNMNY";
            states += "NCNDOHOKORPARISCSDTNTXUTVTVAWAWVWIWY";
            // Include the following to test for Canadian provinces.
            /* Canadian provinces included only if
               a second parameter is supplied and is set to true. */
            if (arguments[1])
               states += "ABBCMBNBNFNSONPEPQSK";
            /* If the string is found in an even position, the state
               is valid. */
            return (0 == (states.indexOf(check) % 2));
         }
      </SCRIPT>
   </HEAD>
   <BODY>
      <LABEL FOR="state">State:</LABEL>
      <INPUT ID="state" TYPE=TEXT SIZE=2 MAXLENGTH=2
         ONCHANGE="this.value = this.value.toUpperCase();
            if (!checkState(this.value)){
               alert(`Invalid State');
            return false;}">
   </BODY>
</HTML>

Validating When the User Submits the Form

You can use submit-time validation to determine whether related information is valid or to ensure that all required information is supplied. For example, if the user indicates that he or she is married, the spouse's name or other information might also be required. The following code demonstrates how to extend the intrinsic text box control with a required attribute to ensure that it is filled in by the user:

<HTML>
   <HEAD>
      <TITLE>Validating When the User Submits the Form</TITLE>
      <SCRIPT LANGUAGE="JavaScript">
         function isEmpty(str) {
            // Check whether string is empty.
            for (var intLoop = 0; intLoop < str.length; intLoop++)
               if (" " != str.charAt(intLoop))
                  return false;
            return true;
         }

         function checkRequired(f) {
            var strError = "";
            for (var intLoop = 0; intLoop<f.elements.length; intLoop++)
               if (null!=f.elements[intLoop].getAttribute("required")) 
                  if (isEmpty(f.elements[intLoop].value))
                     strError += "  " + f.elements[intLoop].name + "\n";
            if ("" != strError) {
               alert("Required data is missing:\n" + strError);
               return false;
            }
         }
      </SCRIPT>
   </HEAD>
   <BODY>
      <FORM NAME="demo" ONSUBMIT="return checkRequired(this);">
         User Name: 
            <INPUT TYPE=TEXT NAME="User Name" required><BR>
         E-Mail Address:
            <INPUT TYPE=TEXT NAME="E-Mail Address" required><BR>
         Age (optional): 
            <INPUT TYPE=TEXT NAME="Age"><BR>
         <INPUT TYPE=SUBMIT VALUE="Submit">
      </FORM>
   </BODY>
</HTML>

Representing Required Information

An extension of the preceding example, demonstrated in the following code, is to initially display required fields with a different background color. As the user fills in those fields, the background color changes back to the default, which helps the user recognize which fields must be completed before submitting the form.

<HTML>
   <HEAD>
      <TITLE>Representing Required Information</TITLE>
      <STYLE TYPE="text/css">
         .required {background: red}
      </STYLE>
      <SCRIPT LANGUAGE="JavaScript">
         function isEmpty(str) {
            for (var intLoop = 0; intLoop<str.length; intLoop++)
               if (" " != str.charAt(intLoop))
                  return false;
            return true;
         }
         function checkRequired(f) {
            for (var intLoop = 0; 
               intLoop<f.elements.length; intLoop++)
               if ("required"==f.elements[intLoop].className) {
                  alert("All red fields are required.");
                  return false;
               }
         }

         function fixUp(el) {
            el.className = isEmpty(el.value) ? "required" : "";
         }
    
         function checkChar(el) {
            if (32 != event.keyCode) 
               el.className = "";
         }
      </SCRIPT>
   </HEAD>
   <BODY> 
      <FORM NAME="demo" ONSUBMIT="return checkRequired(this);">
         User Name: 
            <INPUT TYPE=TEXT CLASS="required" 
               ONKEYPRESS="checkChar(this);" 
               ONCHANGE="fixUp(this);"><BR>
         E-Mail Address: 
            <INPUT TYPE=TEXT CLASS="required" 
               ONKEYPRESS="checkChar(this);" 
               ONCHANGE="fixUp(this);"><BR>
         Age (optional): 
            <INPUT TYPE=TEXT SIZE=3><BR>
         <INPUT TYPE=SUBMIT VALUE="Submit">
      </FORM>
   </BODY>
</HTML>

In this example, the CLASS attribute is used instead of the user-defined required attribute to identify required fields.

Formatting User Input

Just as validation can improve the user's experience by warning of invalid input, formatting user input can make data more usable and readable. The same techniques used to validate data can also be used to format data. Formatting user input can be done while the user types or when the user exits the field. This section shows you how to extend the built-in input controls to add formatting information directly to an element using two custom attributes.

The following code demonstrates a minimal implementation that includes the number-validating routine used earlier plus some simple formatting code to change the style if the number is positive or negative. Although this example only changes the style, a formatter can also be written that customizes the value—for example, by adding digit separators or any other custom format.

<HTML>
   <HEAD>
      <TITLE>Formatting User Input</TITLE>
      <STYLE TYPE="text/css">
         .positive {color:green}
         .negative {color:red} 
         .badValue {background:red; color:white}
      </STYLE>
      <SCRIPT LANGUAGE="JavaScript">
         function formatNumber() {
            with (event.srcElement) 
               className =
                  parseInt(value) >= 0 ? "positive" : "negative";
         }
  
         function validateNumber() {
            // Get the source element.
            var el = event.srcElement;
            var num = "0123456789";  // Valid numbers
            event.returnValue = true;
            // Check first character for negative number.
            event.returnValue = ("-" == el.value.charAt(0)) ||
               (-1 != num.indexOf(el.value.charAt(0)));
            * Loop over remaining contents. If any character 
               is not a number, set the return value to false. */
            for (var intLoop = 1; intLoop < el.value.length;
                  intLoop++)
               if (-1 == num.indexOf(el.value.charAt(intLoop))) 
                  event.returnValue = false;
            if (!event.returnValue)       // Bad value
               el.className = "badValue"; // Change class.
            else
               // Clear class to use default rendering.
               el.className = "";
         }

         function checkFormat() {
            event.returnValue = true;
            if (null != event.srcElement.validate)
               if ("number" == event.srcElement.validate)
                  validateNumber();  // Sets event.returnValue
            if ((null != event.srcElement.getAttribute("format")) &&
                (event.returnValue))
               if ("number" ==
                     event.srcElement.getAttribute("format"))
                  formatNumber();
         }
      </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT TYPE=TEXT ONCHANGE="checkFormat();" format="number" 
         validate="number">
   </BODY>
</HTML>

Using Password Input Controls

A Password field is a text box in which the entire user input is masked with asterisk (*) characters. This masking is useful when the user is typing sensitive information. For security, scripts running under Internet Explorer 4.0 cannot access the true value of the control. Instead, the value property always returns an * for each character the user types. The asterisks allow client-side code to verify that a password has been entered or that the password has a specific number of characters. Key-related events also always return * for all key presses.

When using Password fields, you should use the POST method to submit the data. Otherwise, the password's value will be displayed as the search value in the form's submission. In either case, the value is not encrypted. Furthermore, Netscape Navigator currently exposes the real value entered, rather than asterisks, so Password fields should be used carefully in security-sensitive situations.

[Содержание]