Приглашаем посетить
Державин (derzhavin.lit-info.ru)

Programming List Elements

Programming List Elements

The Select element is used to present a list of options to the user. There are two styles of lists: combo boxes (drop-down lists) and list boxes. These two list styles are generally interchangeable, and their scripting model is identical. The only exception is that the list box style can be used to create a multiple-select list box, which lets the user select multiple list items. Figure 10-1 shows the three types of lists.

Programming List Elements

Figure 10-1. The three types of lists available using the Select element.

Defining a List Box

You create a list box using the Select element. The Select element contains Option elements representing each list item. The three types of list boxes can be created as shown in the following code:

<HTML>
   <HEAD>
      <TITLE>List Types</TITLE>
   </HEAD>
   <BODY>
      <FORM NAME="lists">
         <SELECT NAME="combostore">
            <OPTION VALUE="Computer" SELECTED>Computer</OPTION>
            <OPTION VALUE="Bookstore">Book Store</OPTION>
            <OPTION VALUE="MailOrder">Mail Order</OPTION>
         </SELECT>
         <SELECT NAME="liststore" SIZE=3>
            <OPTION VALUE="Computer" SELECTED>Computer</OPTION>
            <OPTION VALUE="Bookstore">Book Store</OPTION>
            <OPTION VALUE="MailOrder">Mail Order</OPTION>
         </SELECT>
         <SELECT NAME="multistore" SIZE=3 MULTIPLE>
            <OPTION VALUE="Computer" SELECTED>Computer</OPTION>
            <OPTION VALUE="Bookstore">Book Store</OPTION>
            <OPTION VALUE="MailOrder" SELECTED>Mail Order</OPTION>
         </SELECT>
      </FORM>
   </BODY>
</HTML>

Specifying a SIZE attribute results in a list box instead of a combo box. The value of the SIZE attribute determines the number of rows displayed. To create a multiple-select list box, you specify the MULTIPLE attribute. When the MULTIPLE attribute is supplied without a SIZE attribute, a list box with a default size of four rows is automatically created.

Adding Styles to List Boxes

Limited style sheet support is provided for list boxes. The color and background color of each option can be modified using style sheets, which allows you to create visually interesting list boxes or even a color selector:

<HTML>
   <HEAD>
      <TITLE>Color Selector</TITLE>
   </HEAD>
   <BODY>
      <SELECT STYLE="width:75pt">
         <OPTION STYLE="background:red; color:white" VALUE="RED">
            Red
         </OPTION>
         <OPTION STYLE="background:navy; color:white" VALUE="NAVY">
            Navy
         </OPTION>
         <OPTION STYLE="background:black; color:white" VALUE="BLACK">
            Black
         </OPTION>
         <OPTION STYLE="background:white; color:black" VALUE="WHITE">
            White
         </OPTION>
      </SELECT>
   </BODY>
</HTML>

The style for selected items in the list in this example does not change, however.

Relating List Contents to the Submitted Value

The contents of an Option element are displayed on the screen, but this displayed value is not submitted back to the server. Instead, the value attribute is submitted and must also be specified in the <OPTION> tag. In general, when you are using a Select element inside a submittable form, each option should have a value attribute. For lists that are manipulated from script and are not displayed on a form, the value attribute can be used optionally or scripts can rely on the text property directly.

Scripting the List Contents

The options collection exposes the Option elements contained in a Select element. Each option in the collection exposes its attributes as well as the contents between the start and end tags of the Option element, which are exposed through the text property.

Option Elements

The Option elements in the document are an exception in the Dynamic HTML object model because they are not exposed in the document's all collection. Also, the Option element does not expose any extra events or properties beyond its standard sets of attributes and the text property. Instead, the Option element is exposed only through its parent Select element because the Select element owns all the interactions with the list, including events.

Adding and Removing List Elements

You can dynamically add items to or remove items from list boxes. This technique allows the list to be customized in response to user input. To add values to or remove values from a list box, you can use the technique introduced in Chapter 9, "Scripting Individual Elements," for adding and removing image map areas. This section presents a more appropriate alternative.

The options collection supports the ability to dynamically add or remove elements. Elements are created using the createElement method or through the new operator, as shown here:

var elOption = createElement("OPTION");
// or
var elOption = new Option;  // Netscape Navigator supports
                            // this method.

Options are then added to the list box using the add method on the options collection or removed using the remove method on the options collection. Options can also be added or removed by assigning an option directly to an array index or by setting an existing option to null. This technique is supported for Netscape Navigator compatibility. The following code compares using the two techniques on list items in a list box named lb on a form named demo:

var elOption = new Option();
// Add and remove using methods.
document.demo.lb.options.add(elOption, 0); // Add as first item.
document.demo.lb.options.remove(2);        // Remove third item.

// Add and remove using Netscape Navigator-compatible technique.
document.demo.lb.options[0] = elOption;    // Add as first item.
document.demo.lb.options[2] = null;        // Remove third item.

The following code demonstrates how to dynamically generate a list box that lists all the bookmarks on the page. When the user selects an item from the list, the document automatically scrolls the bookmark into view.

<HTML>
   <HEAD>
      <TITLE>Bookmark List</TITLE>
      <SCRIPT LANGUAGE="JavaScript">
         function addNew(text, value) {
            // Add a new option. 
            var el = document.createElement("OPTION");
            el.text = text;
            el.value = value;
            document.all.bm.options.add(el);
         }

         function buildList() {
            /* When adding a new list item, the text is the contents
               of the anchor and the value is the name of the
               bookmark. The value is used to scroll the element into
               view. */
            for (var intLoop = 0; intLoop < document.anchors.length;
                  intLoop++) 
               addNew(document.anchors[intLoop].innerText,
                      document.anchors[intLoop].name);
         }

         function scrollit(where) {
            // Scroll the specified bookmark into view.
            document.all[where.value].scrollIntoView();
            // Reset list box.
            where.value = null;
         }
      </SCRIPT>
   </HEAD>
   <BODY ONLOAD="buildList();">
      <LABEL FOR="bm">Bookmarks: 
      <SELECT ID=bm STYLE="width:100pt" ONCHANGE="scrollit(this);">
      </SELECT>
      <H1><A NAME="Contents">Contents</A><H1>
      Table of Contents
      <H2><A NAME="Abstract">Abstract</A></H2>
      About this document
      <H2><A NAME="Chapter1">Chapter 1</A></H2>
      Chapter 1
      <H2><A NAME="Summary">Summary</A></H2>
      Summary contents
   </BODY>
</HTML>

Scripting Multiple-Select List Boxes

Multiple-select list boxes allow the user to select more than one item from a list. In a multiple-select list box, the value property returns only the first selected item. To determine all the selected items, the entire list of options must be enumerated using a script. The following function demonstrates how to build an array of selected items for any list box. (If you use this function with a single-select list box, the resulting array will contain only a single value.)

<SCRIPT LANGUAGE="JavaScript">
   function getSelected(opt) {
      var selected = new Array();
      var index = 0;
      for (var intLoop=0; intLoop < opt.length; intLoop++) {
         if (opt[intLoop].selected) {
            index = selected.length;
            selected[index] = new Object;
            selected[index].value = opt[intLoop].value;
            selected[index].index = intLoop;
         }
      }
      return selected;
   }
</SCRIPT>

Using Check Boxes for Small Lists

If the number of options is small, it might make more sense to use a set of check boxes instead of a multiple-select list box. By sharing the same name across each check box in the set, the check boxes will have the same submit behavior as the multiple-select list box. The preceding function can be rewritten as shown in the following code to determine which check boxes are selected. Rather than enumerating the options collection contained in the Select element, however, you must enumerate the Form elements with a given name. Instead of passing an options collection to the function, the collection of check boxes is used. Another distinction is that check boxes expose a checked property for determining whether they are selected, while the list box uses the selected property, so the conditional logic in the function tests for either selected or checked.

<HTML>
   <HEAD>
      <TITLE>Multiple-Select Check Boxes</TITLE>
      <SCRIPT LANGUAGE="JavaScript">
         function getSelected(opt) {
            var selected = new Array();
            var index = 0;
            for (var intLoop = 0; intLoop < opt.length; intLoop++) {
               if ((opt[intLoop].selected) ||
                   (opt[intLoop].checked)) {
                  index = selected.length;
                  selected[index] = new Object;
                  selected[index].value = opt[intLoop].value;
                  selected[index].index = intLoop;
               }
            }
            return selected;
         }

         function outputSelected(opt) {
            var sel = getSelected(opt);
            var strSel = "";
            for (var item in sel)       
               strSel += sel[item].value + "\n";
            alert("Selected Items:\n" + strSel);
         }
      </SCRIPT> 
   </HEAD>
   <BODY> 
      <FORM NAME="ColorSelector">
         <INPUT TYPE=CHECKBOX NAME="color" VALUE="Red">Red
         <INPUT TYPE=CHECKBOX NAME="color" VALUE="Navy" CHECKED>Navy
         <INPUT TYPE=CHECKBOX NAME="color" VALUE="Black">Black
         <INPUT TYPE=CHECKBOX NAME="color" VALUE="White" CHECKED>White
         <INPUT TYPE=BUTTON VALUE="Selected Check Box Items" 
            ONCLICK="outputSelected(this.form.color);">
         <P>
         <SELECT NAME="multistore" SIZE=3 MULTIPLE>
            <OPTION VALUE="Computer" SELECTED>Computer</OPTION>
            <OPTION VALUE="Bookstore">Book Store</OPTION>
            <OPTION VALUE="MailOrder" SELECTED>Mail Order</OPTION>
         </SELECT>
         <INPUT TYPE=BUTTON VALUE="Selected List Items" 
            ONCLICK="outputSelected(this.form.multistore.options)">
      </FORM>
   </BODY>
</HTML>

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