Приглашаем посетить
Маркетплейс (market.find-info.ru)

10.2 Controlling input elements with DOM interfaces

Table of Contents

Previous Next

10.2 Controlling input elements with DOM interfaces

10.2.1 Generating text field, button, radio, and checkbox

Some of the most popular interface elements on the Web are "Text Box," "Button," "Radio Box," and "Check Box." In order to get user input and to interact with the user, these boxes are important and usually implemented by using the HTML/XHTML <input> element. For example, the statement



<input type="text" class="styleSt" value="My Text Box" />

is often used to generate a text field (or text box) to get text input. This text field contains some CSS properties and has an initial value as "My Text Box." You can, of course, change the value by typing something else on the page. Different type attributes would generate different input elements. Some of the most frequently used types are:

type="text"

Generates a text field.

type="button"

Generates a button.

type="radio"

Generates a radio box.

type="checkbox"

Generates a checkbox.


With the W3C DOM, these elements can be studied in a systematic way. First, consider the following page on how to generate these input elements:



Example: ex10-01.htm - Generating Input Boxes

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <style>
 6:   .styleSt{width:280px;height:35px;background:#aaffaa;font-family:arial;
 7:   font-weight:bold;font-size:18pt;color:#880000}</style>
 8: <head><title>Generating Input Boxes -- ex1001.htm</title></head>
 9: <body style="background:#000088;font-family:arial;font-size:22pt;
10:      color:#ffff00;font-weight:bold;text-align:center"><br />
11:    Generating Input Boxes<br /><br />
12:
13: <table style="font-size:18pt;font-weight:bold;text-align:left">
14:  <tr><td>A Button: </td><td>
15:    <input type="button" value="This is a Button"
16:           class="styleSt" style="background:#cccccc" /></td></tr>
17:    <tr><td>A Text Box: </td><td>
18:      <input type="text" value="This is a Text Box" class="styleSt"
19:           style="color:#000000;background:#ffffff"/></td></tr>
20:    <tr><td>A Radio Button: </td><td>
21:    <input type="radio" class="styleSt" name="radB" style="width:40px" />
22:    <input type="radio" class="styleSt" name="radB" style="width:40px" />
23:  </td></tr><tr><td>A CheckBox: </td><td>
24:    <input type="checkbox" class="styleSt" style="width:40px" />
25:    <input type="checkbox" class="styleSt" style="width:40px" /></td></tr>
26: </table>
27: </body>
28: </html>

This page is quite simple. It generates four kinds of input boxes using the <input> element. Four different input types are used: "text," "button," "radio," and "checkbox." The statements defined in lines 15 and 18 generate a button and a text field. Two radio boxes are then defined and finally two checkboxes are drawn in lines 2425. They all have CSS properties attached to them and are organized by a table element. Note that the radio boxes (lines 2122) have the same name="radB" so that only one selection can be picked at any time. A screen shot of this page is shown in Fig. 10.1.

Figure 10.1. ex10-01.htm

graphics/10fig01.jpg


XHTML as a language does not specify any implementations or procedures on how to handle these input elements after displaying them on the screen. To control these boxes and use them in our applications, we need to know:

  • How to gain access to the user input such as the text in the text box.

  • How to get the selection of the radio boxes.

  • How to pick up values of all the checked boxes.

The answers are provided by the interfaces of the DOM.

10.2.2 The DOM interface for input elements

Prior to the W3C recommendations, the implementations on how to handle input elements beyond XHTML level were mostly proprietary. They were either inconsistent or incomplete. With the W3C DOM (www.w3.org), the DOM in general works by providing a series of interfaces to cover from top to bottom every element of the XHTML language. The interface for input elements is called "Interface HTMLinputElement" and was originally designed for the HTML. It is fully embedded and compatible with our XHTML discussions. The definition of this interface for input elements is



Listing: ex10-02.txt - The DOM Interface For Input Elements

 1: interface HTMLInputElement : HTMLElement {
 2:            attribute DOMString        defaultValue;
 3:            attribute boolean          defaultChecked;
 4:   readonly attribute HTMLFormElement  form;
 5:            attribute DOMString        accept;
 6:            attribute DOMString        accessKey;
 7:            attribute DOMString        align;
 8:            attribute DOMString        alt;
 9:            attribute boolean          checked;
10:            attribute boolean          disabled;
11:            attribute long             maxLength;
12:            attribute DOMString        name;
13:            attribute boolean          readOnly;
14:            attribute DOMString        size;
15:            attribute DOMString        src;
16:            attribute long             tabIndex;
17:   // Modified in DOM Level 2:
18:            attribute DOMString        type;
19:            attribute DOMString        useMap;
20:            attribute DOMString        value;
21:   void               blur();
22:   void               focus();
23:   void               select();
24:   void               click();
25: };

Lines 220 are the attributes (or properties) of this interface. The remaining lines are the member functions that you can call within this interface object. The attributes are in line with the attributes defined inside the <input> element of the XHTML language. For example, you can define a disabled button using XHTML language as:



<input type="button" disabled onclick="myFun()" id="but" />

To activate this button, the disabled attribute defined in line 10 can be used as follows:



<script> document.getElementById("but").disabled=false</script>

In this section, we restrict our discussion to the type (line 18) "text," "password," "button," "radio," and "checkbox."

There is an independent interface for buttons called "Interface HTMLButtonElement" so that buttons can be defined as independent elements and to access them. The attributes of the button interface are, however, included in this input element interface. For the types concerned, we consider some frequently used properties and functions and show how to master them in a professional way.

value (line 20) is a string variable (DOMString is basically a string)

  • When the type equals "Text," "Button," "File," or "Password," this represents the current contents of the element.

readOnly (line 13) is a Boolean variable (true or false)

  • This control is read-only and only applies to type "text" or "password."

disabled (line 10) is a Boolean variable

  • This will make the element unavailable.

checked (line 9) is a Boolean variable

  • Mainly used when the type equals "radio" or "checkbox," this represents the current selection of the associated box.

focus() (line 22) is a function to provide keyboard focus to the element.

The best way to demonstrate how to use these properties is to look at some practical applications.

10.2.3 Controlling text fields and buttons

Text fields and buttons are one of the most widely used interfaces in the Web programming industry. Together with radio, checkbox, select box, and text area, you have a set of handy Web programming tools. To generate and use these tools is easy, although more experience may be needed if you want to master them confidently and to put them into your applications. A good place to start is to learn some combination skills involving text fields and buttons.

In the next example, two text fields and some buttons are developed. We demonstrate how to use the readOnly attribute to make a text field read-only so that information cannot be modified. This technique is often used by professionals to minimize user errors. The focus() function is also employed to show how to move your keyboard cursor to a text field for typing purposes. One characteristic of this example is that buttons can change their names and actions.



Example: ex10-02.htm - Controlling Text Fields And Buttons (DOM)

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title> Text Fields and Buttons I -- ex1002.htm</title></head>
 6: <style>
 7:   .butSt{background-color:#aaaaaa;font-family:arial;font-weight:bold;
 8:      font-size:14pt;color:#aa0000;width:150px;height:35px}
 9:   .txtSt{background-color:#aaffaa;font-family:arial;font-weight:bold;
10:      font-size:16pt;color:#880000;width:300px;height:35px}
11:   .txtSt2{font-family:arial;font-weight:bold; text-align:left;
12:      font-size:14pt;color:#ffff00}
13: </style>
14: <body style="background:#000088;font-size:20pt;text-align:center"
15: class="txtSt2"><br />Simple Controls On Text Field<br /><br />
16:
17: <div class="txtSt2" style="text-align:center"><br />
18:   <span>Text Field 1: </span>
19:   <input type="text" id="myText1" name="myText1"
20:      value="This is Text Field 1" class="txtSt" /><br /><br />
21:   <span>Text Field 2: </span>
22:   <input type="text" id="myText2" name="myText2"
23:     value="This is Text Field 2" class="txtSt" /><br /><br /><br />
24:
25:   <table class="txtSt2" align="center">
26:   <tr>
27:     <td>Text1 Control<br /> Buttons</td>
28:     <td><input type="button" id="readBut1" onclick="readOnlyTxt(1)"
29:          value="ReadOnly" class="butSt" /></td>
30:     <td><input type="button" onclick="focusTxt(1)"
31:          value="Focus" class="butSt" /></td></tr>
32:   <tr>
33:     <td>Text2 Control<br /> Buttons</td>
34:     <td><input type="button" id="readBut2" onclick="readOnlyTxt(2)"
35:          value="ReadOnly" class="butSt" /></td>
36:     <td><input type="button" onclick="focusTxt(2)"
37:          value="Focus" class="butSt" /></td></tr>
38:  </table>
39: </div>
40: <script src="ex10-02.js"></script>
41: </body>
42: </html>

Two input elements with type="text" are defined in lines 1823. These two text fields are controlled by two rows of buttons. Consider the two buttons in the first row (lines 2831):



<input type="button" id="readBut1" onclick="readOnlyTxt(1)"
   value="ReadOnly" class="butSt" />

<input type="button" onclick="focusTxt(1)"
          value="Focus" class="butSt" />

When the first button is pressed, the function readOnlyTxt(1) performs the following actions:

  • It sets the first text field as read-only so that no modifications can be made.

  • It changes the color of the read-only text field.

  • It changes the button to "Read and Write" so that the text field can be changed back again by another click.

The second button is to move the keyboard cursor into the first text field by calling the function focusTxt(1). The second row of buttons (lines 3337) is used to control the second text field in a similar fashion. Some screen shots of this example are shown in Figs 10.2 and 10.3.

Figure 10.2. ex10-02.htm

graphics/10fig02.jpg


Figure 10.3. Controlling buttons and text fields

graphics/10fig03.jpg


The program file for this example is ex10-02.js and listed below.



Example: ex10-02.js - The ECMAScript For ex1002.htm

 1: function focusTxt(llV)
 2: {
 3:   objV = "myText"+llV
 4:   document.getElementById(objV).focus()
 5: }
 6:
 7: var readonlyV1 = 0
 8: var readonlyV2 = 0
 9:
10: function readOnlyTxt(llV)
11: {
12:  if (llV ==1) {
13:   if (readonlyV1 ==0 ) {
14:    readonlyV1 = 1
15:    objV = "myText"+llV
16:    document.getElementById(objV).readOnly = true
17:    document.getElementById(objV).style.color="#888888"
18:    document.getElementById("readBut1").value="Read & Write"
19:   } else {
20:    readonlyV1 = 0
21:    objV = "myText"+llV
22:    document.getElementById(objV).readOnly = false
23:    document.getElementById(objV).style.color="#880000"
24:    document.getElementById("readBut1").value="ReadOnly"
25:   }
26:  } else {
27:   if (readonlyV2 ==0 ) {
28:    readonlyV2 = 1
29:    objV = "myText"+llV
30:    document.getElementById(objV).readOnly = true
31:    document.getElementById(objV).style.color="#888888"
32:    document.getElementById("readBut2").value="Read & Write"
33:   } else {
34:    readonlyV2 = 0
35:    objV = "myText"+llV
36:    document.getElementById(objV).readOnly = false
37:    document.getElementById(objV).style.color="#880000"
38:    document.getElementById("readBut2").value="ReadOnly"
39:   }
40:  }
41: }

This listing contains two functions. The first one is focusTxt(llV). It takes an argument and the statements inside the function are



objV = "myText"+llV
document.getElementById(objV).focus()

The first statement is to compose the identity of the object. Then the focus() function is called to move the keyboard cursor to that element.

The code for the second function readOnlyTxt(llV) is longer. First, global variables readonlyV1 and readonlyV2 are used to store the current read-only status of the text fields. A zero value indicates a "Read & Write" situation and "Read Only" otherwise. If the function readOnly(llV) is called with argument llV=1, the first text field is considered and the following statements (lines 1326) are executed:



 if (readonlyV1 ==0 ) {
  readonlyV1 = 1
  objV = "myText"+llV
  document.getElementById(objV).readOnly = true
  document.getElementById(objV).style.color="#888888"
  document.getElementById("readBut1").value="Read & Write"
 } else {
  readonlyV1 = 0
  objV = "myText"+llV
  document.getElementById(objV).readOnly = false
  document.getElementById(objV).style.color="#880000"
  document.getElementById("readBut1").value="ReadOnly"
 }
}

That is, if the first text field is "Read & Write," it is changed to read-only. The color of the text field and the name of the button are changed as well. If the current status of the text field is "Read Only," the statements after the else keyword are executed. In this case, the readOnly status of the text field is set to false so that user input can be accepted. The color and the name of the button are also changed at the same time.

Manipulating text attributes such as readOnly with programming techniques is popular among professionals since they are one of the important tools to eliminate unnecessary user errors.

To show how to capture data from text boxes, we consider another example: ex10-03.htm. In terms of page design and structure, this example is similar to ex10-02.htm. We also have two text fields and four buttons arranged into two rows. The first button captures the text of the first text field and outputs the data to a dedicated area. The second button is used to make the text field disappear entirely. The third and fourth buttons control the second text field. Consider the XHTML code fragment of this example below:



Listing: ex10-03.txt - Page Fragment For ex1003.htm

 1:  <table class="txtSt2" align="center">
 2:   <tr>
 3:     <td>Text1 Control<br /> Buttons</td>
 4:     <td><input type="button" id="showTxt1" onclick="showTxt(1)"
 5:          value="Show Text" class="butSt"></td>
 6:     <td><input type="button" id="disappTxt1" onclick="disappTxt(1)"
 7:          value="Disappear" class="butSt"></td></tr>
 8:   <tr>
 9:     <td>Text1 Control<br /> Buttons</td>
10:     <td><input type="button" id="showTxt2" onclick="showTxt(2)"
11:          value="Show Text" class="butSt"></td>
12:     <td><input type="button" id="disappTxt2" onclick="disappTxt(2)"
13:          value="Disappear" class="butSt"></td></tr>
14:  </table><br /><br />
15:
16:   <input type="text" id="outMsg" name="outMsg" readOnly="true"
17:     value="Text Field Message" class="txtSt"/><br />
18: </div>
19: <script src="ex1003.js"></script>
20:

If you replace lines 2540 in ex10-02.htm with this fragment, you will have the XHTML code for. ex10-03.htm. Basically, this fragment changes the names of the buttons and the functions associated with them. If you press the button defined in line 4, the function showTxt(1) is called to capture the text in "Text Field 1" and displays it to the message area in lines 1617. If the second button is pressed, the function disappTxt(1) is called and makes the entire "Text Field 1" disappear. These two functions are specified in the program file ex10-03.js.



Example: ex10-03.js - The ECMAScript For ex1003.htm

 1: function showTxt(llV)
 2: {
 3:   objV = "myText"+llV
 4:   document.getElementById("outMsg").value =
 5:   document.getElementById(objV).value
 6: }
 7:
 8: var disappV1 = 0
 9: var disappV2 = 0
10:
11: function disappTxt(llV)
12: {
13:  if (llV ==1) {
14:   if (disappV1 ==0 ) {
15:    disappV1 = 1
16:    objV = "myText"+llV
17:    document.getElementById("disappTxt1").value="Appear"
18:    document.getElementById(objV).style.visibility="hidden"
19:   } else {
20:    disappV1 = 0
21:    objV = "myText"+llV
22:    document.getElementById("disappTxt1").value="Disappear"
23:    document.getElementById(objV).style.visibility="visible"
24:   }
25:  } else {
26:   if (disappV2 ==0 ) {
27:    disappV2 = 1
28:    objV = "myText"+llV
29:    document.getElementById("disappTxt2").value="Appear"
30:    document.getElementById(objV).style.visibility="hidden"
31:   } else {
32:    disappV2 = 0
33:    objV = "myText"+llV
34:    document.getElementById("disappTxt2").value="Disappear"
35:    document.getElementById(objV).style.visibility="visible"
36:   }
37:  }
38: }

The function showTxt() is easy to understand. The document.getElementById(objV).value captures the content of the text field and the statement in line 4 displays it to the area with id="outMsg". The disappTxt() function uses the CSS property



document.getElementById(objV).style.visibility="hidden"

to make the text field disappear (line 18). Some screen shots are shown in Figs 10.4 and 10.5.

Figure 10.4. ex10-03.htm

graphics/10fig04.jpg


Figure 10.5. Controlling buttons and text fields (II)

graphics/10fig05.jpg


You now have some hands-on experiences to handle input elements. It is time to consider a real application. The next section shows you how to change your password.

10.2.4 A page to change your password

Providing facilities to change a password is a general application on the Web. From the membership of a kids club to the Internet banking and commercial sectors, a simple and friendly facility to allow users to change their passwords regularly is considered to be a good security measure. We are not going to discuss Internet security, at least not yet, just a simple facility to allow users to change their passwords.

Even a basic facility to change a password involves the following operations. You need to

  • generate a text field for the password and capture the password data;

  • capture the keystroke, in particular the carriage return (ASCII value 13) so that you know the user has finished typing and further action is needed;

  • generate a confirm password window at run time to allow the user to retype the password; and

  • compare the password and the confirm data for a match.

To make this example more interesting, no inline event handlers are set up to capture the keystroke, event listener techniques are used instead. In order to handle the differences of the IE, NS, and some backward compatibility issues, two sets of coding are used together with a simple detection routine to detect the IE and NS browsers.

The interface part of this page is simple and is listed below:



Example: ex10-04.htm - A Page To Change Password

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title> A Page To Change Password -- ex1004.htm</title></head>
 6: <style>
 7:   .butSt{background-color:#aaffaa;font-family:arial;font-weight:bold;
 8:      font-size:18pt;color:#880000;width:250px;height:35px}
 9:   .txtSt{font-family:arial;font-weight:bold; text-align:left;
10:      font-size:14pt;color:#ffff00}
11: </style>
12: <body style="background:#000088">
13:
14: <table style="position:absolute;left:60px;top:50px;
15:           font-size:18pt" class="txtSt">
16:  <tr><td colspan="2" style="text-align:center">
17:      Changing Your Password<br /><br/></td></tr>
18:  <tr><td>Name:</td>
19:      <td><input type="text" id="nameSt" class="butSt" ></td></tr>
20:  <tr><td>New Password:</td>
21:      <td><input type="password" id="passSt" class="butSt"></td></tr>
22:  <tr style="visibility:hidden" id="confirm"><td>Confirm Password:</td>
23:      <td><input type="password" id="confirmSt" class="butSt" ></td></tr>
24:  <tr><td colspan="2"><br /><br />
25:      <div id="outMsg" class="txtSt"></div></td></tr>
26: </table>
27:
28: <script src="ex10-04.js"></script>
29: </body>
30: </html>

In this page, we use a table to accommodate text fields on "Name" (line 19), "New Password" (line 21), and "Confirm Password" (line 23). The new password and confirm password have the attribute type="password" so that the content will not be displayed on screen.

The "Confirm Password" element defined in line 22 has the initial CSS property visibility:hidden so that the entire row will not be displayed at all.

In a normal change password operation, we would like to implement the following features:

  • When the user finishes typing his or her name in the "Name" field and hits the return key, the keyboard cursor will jump to the "New Password" field.

  • When the user finishes typing the password and hits the return key, a "Confirm Password" text field appears and focus on this field.

  • As soon as the user finishes the confirm password and hits the return key again, the new password and the confirmed one are compared to check for a match.

  • The matching result is displayed in a dedicated display area defined in line 25.

Some screen shots of this example in action are shown in Figs 10.610.9.

Figure 10.6. ex10-04.htm

graphics/10fig06.jpg


Figure 10.9. Password not accepted

graphics/10fig09.jpg


Figure 10.7. Generating confirm password at run time

graphics/10fig07.jpg


Figure 10.8. Password accepted

graphics/10fig08.jpg


The driving force behind the interface is the external ECMAScript ex10-04.js and the first part of this program is listed below:



Example: ex10-04.js - The ECMAScript For ex1004.htm (Part One)

 1:
 2:  var IE = document.all?true:false
 3:  var objV
 4:  if (!IE)
 5:  {
 6:     objV1 = document.getElementById("nameSt")
 7:     objV1.addEventListener("keypress",proName,false)
 8:     objV2 = document.getElementById("passSt")
 9:     objV2.addEventListener("keypress",proNew,false)
10:     objV3 = document.getElementById("confirmSt")
11:     objV3.addEventListener("keypress",proConfirm,false)
12:  }else {
13:     objV1 = document.getElementById("nameSt")
14:     objV1.attachEvent("onkeypress",proName)
15:     objV2 = document.getElementById("passSt")
16:     objV2.attachEvent("onkeypress",proNew)
17:     objV3 = document.getElementById("confirmSt")
18:     objV3.attachEvent("onkeypress",proConfirm)
19:  }
20:
21:  function chkReturn(e)
22:  {
23:   if (IE) {
24:       if (escape(event.keyCode)=="13") return true
25:   } else {
26:       if (escape(e.keyCode) == "13") return true
27:       else return false
28:   }
29:  }
30:

This part of the program is to set up the event listeners. The first line detects the browser type. If the NS (NS6+) browser is detected, the statements in lines 611 are used to set up the event listeners. Similarly the execution of statements in lines 1318 sets the listeners for IE-type browsers.

Since we need to listen to the keystrokes on the "Name," "New Password," and "Confirm Password" fields, three listeners are set. When any keystroke is detected in the "Name" field, the function proName() is called to process the name. If a carriage return key is found, the function is to move the keyboard cursor to the next field.

The function chkReturn() defined in lines 2129 is designed to trap the carriage return key which has the ASCII value 13. This function returns a true value when ASCII 13 code is detected. Again two sets of code are used. The second part of the ECMAScript ex10-04.js contains all the process functions for the page ex10-04.htm.



Listing: Continuation Of The ECMAScript ex1004.js (Part Two)

31:  function proName(e)
32:  {
33:   if (chkReturn(e)) document.getElementById("passSt").focus()
34:  }
35:
36:  function proNew(e)
37:  {
38:   if (chkReturn(e)) {
39:    document.getElementById("confirm").style.visibility="visible"
40:    document.getElementById("confirmSt").focus()
41:   }
42:  }
43:
44:  function restorePar(e)
45:  {
46:      document.getElementById("nameSt").value =""
47:      document.getElementById("passSt").value =""
48:      document.getElementById("confirmSt").value=""
49:
50:      document.getElementById("nameSt").focus()
51:      document.getElementById("confirm").style.visibility = "hidden"
52:  }
53:
54:  function proConfirm(e)
55:  {
56:   if (chkReturn(e))
57:   {
58:    ISt01 = document.getElementById("confirmSt").value
59:    ISt02 = document.getElementById("passSt").value
60:    if ( ISt01 != ISt02) {
61:     outSt = "Passwords Do Not Match! <br />"+ "Please Re-enter Your Password"
62:    } else {
63:      outSt = "Password Accepted"
64:    }
65:    document.getElementById("outMsg").innerHTML= outSt
66:    restorePar()
67:   }
68:  }

The first function proName() is simple. If the keystroke is the return key, the focus() function sets the cursor to the "New Password" field. The second function proNew() is called whenever a key event occurs inside the new password field. If the return key is detected, the statement in line 39 is executed to make the entire row with identity id="confirm" visible so that the "Confirm Password" field appears. The statement in line 40 is to focus on the confirm box. If the user hits the return key inside the confirm box, the proConfirm() function compares the password data and the data in the confirm field. If they are the same, the statement in 65 displays the message "Password Accepted." Whether you have a matched password or not, the function restorePar() is called to reset all the text field attributes.

    Table of Contents

    Previous Next