Приглашаем посетить
Гумилев (gumilev.lit-info.ru)

10.4 Select boxes and their applications

Table of Contents

Previous Next

10.4 Select boxes and their applications

10.4.1 The DOM interface for select box

The next DOM interface that we want to talk about is the select box interface. It can be used to access a select box. Select box, sometimes called combo box, is defined in HTML/XHTML specifications as an independent element. To generate a select box, the <select> element is used. A typical example to generate a select box is shown in ex10-08.htm.



Example: ex10-08.htm - Generating A Select Box

 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:   .selSt{width:280px;height:35px;background:#aaffaa;
 7:     font-family:arial;font-weight:bold;font-size:18pt;color:#880000}
 8: </style>
 9: <head><title>Generating A Select Box -- ex1008.htm</title></head>
10: <body style="background:#000088;font-family:arial;font-size:22pt;
11:      color:#ffff00;font-weight:bold;text-align:center"><br />
12: Generating A Select Box<br /><br />
13:
14:   <select id="mySelectBox" name="mySelectBox" class="selSt">
15:    <option>First Option</option>
16:    <option>Second Option</option>
17:    <option>Third Option</option>
18:    <option>fourth Option</option>
19:  </select>
20:
21: </body>
22: </html>

The <select> element defined in lines 1419 generates a select box on the screen and all the option elements <option > in lines 1518 form a series of pull-down selections.

Before the W3C DOM standardization, the ways of controlling select boxes were mostly proprietary. For different browsers, you may need different techniques to gain access to the selected item. With the W3C DOM, we have a standard interface to control this box. A simplified definition of this interface is given below.



Listing: ex10-05.txt - DOM Interface For Select Box

 1: interface HTMLSelectElement : HTMLElement {
 2:   readonly attribute DOMString        type;
 3:            attribute long             selectedIndex;
 4:            attribute DOMString        value;
 5:   readonly attribute long length;
 6:   readonly attribute HTMLFormElement  form;
 7:   readonly attribute HTMLCollection   options;
 8:            attribute boolean          disabled;
 9:            attribute boolean          multiple;
10:            attribute DOMString        name;
11:            attribute long             size;
12:            attribute long             tabIndex;
13:   void               add(in HTMLElement element,
14:                          in HTMLElement before)
15:                                         raises(DOMException);
16:   void               remove(in long index);
17:   void               blur();
18:   void               focus();
19: };

Again we will not explain this interface line by line. A detailed definition of this interface is provided in the DOM document of W3C. For our practical purposes, we concentrate on the following properties and functions:

selectedIndex

  • The ordinal index of the selected option, starting from 0. The value 1 is returned if no element is selected.

length

  • The number of options in the select.

options

  • The collection of option elements contained by this element.

void add (in HTMLElement element, in HTMLElement before)

  • Add a new element to the collection of option elements for this select.

void remove (in long index)

  • Remove an element from the collection of option elements for this select. Does nothing if no element has the given index.

To understand and use these features, let's consider a page to offer discount holidays on the Web using select boxes.

10.4.2 A page to offer discount holidays

A more general discussion on the structure of the DOM and its related interfaces is given in the next chapter. In this section, some basic controlling and accessing techniques that relate to the select box are discussed. Consider the following page offering special discount holidays to potential customers:



Example: ex10-09.htm - A Page To Offer Discount Holidays

 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> .selSt{width:380px;height:35px;background:#aaffaa;
 6:   font-family:arial;font-weight:bold;font-size:16pt;color:#880000}</style>
 7: <head><title>Offering Discount Holidays -- ex1009.htm</title></head>
 8: <body style="background:#000088;font-family:arial;font-size:22pt;
 9:      color:#ffff00;font-weight:bold;text-align:center"><br />
10: Special 25% Discount <br />Holiday Offer<br /><br />
11:
12: <div style="position:absolute;top:160px;left:60px;text-align:left;
13:  font-size:18pt">Holiday Packages<br />
14:   <select id="holiday" name="holiday" class="selSt">
15:    <option />London and Paris (10 Nights)
16:    <option />New York (7 Nights)
17:    <option />Los Angeles (7 Nights)
18:    <option />Rome and Italy (10 Nights)
19:    <option />Hong Kong and Thailand (10 Nights)
20:    <option>Japan and China (14 Nights)</option>
21:   </select><br /><br /><br /><br />
22:   <div id="outMsg"></div>
23: </div>
24:  <input type="button" value="Order" onclick="orderHoliday()"
25:     style="position:absolute;top:165px;left:460px;width:100px;
26:     height:60px;font-family:arial;font-size:18pt;font-weight:bold" />
27:  </body>
28:  <script>
29:  function orderHoliday()
30:  {
31:    llV = document.getElementById("holiday")
32:    selectV = llV.selectedIndex
33:    llSt = "You Have Selected The Holiday Package: "+selectV +"<br />"
34:    llSt = llSt + "Which Is:"+ llV.options.item(selectV).firstChild.data
35:    document.getElementById("outMsg").innerHTML=llSt
36:  }
37: </script>
38: </html>

Again, the select element <select> in lines 1421 generates a select box on the page and all the option elements between lines 15 and 20 form a series of pull-down selections. Buttons, select boxes, and many other boxes can have CSS properties to enhance their look and feel. In this example, the select box has an identity id="holiday" which provides some special discount holiday offers to customers.

Once the Order button defined in lines 2426 is clicked, the function orderHoliday() is called. To access the selected choice, all you have to do is to get hold of the property selectedIndex. More precisely, you have the following statement by combining the codes in lines 3132:



document.getElementById("holiday").selectedIndex

Since the selectedIndex variable only reflects the position of the selection which starts from 0, its value is a number. For example, if you pick the "London and Paris (10 Nights)" option, the selectedIndex has a value of 0. The selectedIndex will have a value of 5 if you pick "Japan and China (14 Nights)." Some screen shots of this example are shown in Figs 10.14 and 10.15.

Figure 10.14. ex10-09.htm

graphics/10fig14.jpg


Figure 10.15. Controlling a select box

graphics/10fig15.jpg


A common technique to convert the option position to the actual data is to use the array structure. For the select box, the DOM interface provides an options property for you to gain direct access to the text of the option. For example, once you have the selected number stored in selectV in line 32, the combination of the firstChild.data returns the selected data, i.e.,



selectV = llV.selectedIndex
llV.options.item(selectV).firstChild.data

Sometimes, the ability to change the options list at run time can produce an impressive effect and appeals to visitors and customers. In the next example, we show you how to change the option string at run time.

10.4.3 Controlling text area and select boxes

Text area is a handy tool to allow users to type in a long paragraph of information. Compared to the select box, text area has a relatively simple format and the interface is listed in ex10-06.txt.



Listing: ex10-06.txt - DOM Interface For Text Area

 1: interface HTMLTextAreaElement : HTMLElement {
 2:            attribute DOMString        defaultValue;
 3:   readonly attribute HTMLFormElement  form;
 4:            attribute DOMString        accessKey;
 5:            attribute long             cols;
 6:            attribute boolean          disabled;
 7:            attribute DOMString        name;
 8:            attribute boolean          readOnly;
 9:            attribute long             rows;
10:            attribute long             tabIndex;
11:   readonly attribute DOMString        type;
12:            attribute DOMString        value;
13:   void               blur();
14:   void               focus();
15:   void               select();
16: };

To define a textarea with XHTML, the following statement is often used:



<textarea id="myTxtArea" cols="60" rows="10">This is my text area
</textarea>

The cols and rows attributes are character based and therefore the statement above defines textarea with 10 rows and each row is 60 characters long. The initial value is the string "This is my text area."

To access textarea, the DOM property value in line 12 is often used. As a practical example, we look at an example to combine textarea with select boxes. Consider the page given below:



Example: ex10-10.htm - Text Area and Select 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:  .areaSt{background:#aaffaa;font-family:arial;font-weight:bold;
 7:     width:500px;height:200px;font-size:16pt;color:#880000;
 8:     position:absolute;left:100px;top:100px}
 9:  .butSt{background-color:#aaffaa;font-family:arial;font-weight:bold;
10:     font-size:14pt;color:#880000;width:120px;height:28px}
11: </style>
12: <head><title> Text Area and Select Boxes -- ex1010.htm</title></head>
13: <body style="background:#000088;font-family:arial;font-size:22pt;
14:         color:#ffff00;font-weight:bold;text-align:center"><br />
15:    Generating and Controlling Text Area<br /><br />
16: <textarea cols="60", rows="9" class="areaSt" id="myTxtArea">
17:
18:   "The Document Object Model is a platform-
19:    and language-neutral interface that will
20:    allow programs and scripts to dynamically
21:    access and update the content, structure,
22:    and style of documents."
23:    (www.w3.org)
24:
25: </textarea>
26: <table style="position:absolute;left:90px;top:320px;font-size:14pt">
27:  <tr><td>Font Color:</td>
28:    <td><select onchange="changeCSS()" id="colIdx" class="butSt">
29:    <option>#880000</option><option>#008800</option>
30:    <option>#000088</option></select></td></tr>
31:  <tr><td>Bg. Color:</td>
32:    <td><select onchange="changeCSS()" id="bgIdx" class="butSt">
33:    <option>#aaffaa</option><option>#ffaaaa</option>
34:    <option>#aaaaff</option></select></td></tr>
35:  <tr><td>Font Size:</td>
36:    <td><select onchange="changeCSS()" id="sizeIdx" class="butSt">
37:    <option>16pt</option><option>12pt</option>
38:    <option>14pt</option></select></td></tr>
39:  <tr><td>Font Family:</td>
40:    <td><select onchange="changeCSS()" id="famIdx" class="butSt">
41:    <option>Arial</option><option>Times</option></select></td></tr>
42: </table>
43:
44: <table style="position:absolute;left:360px;top:330px;font-size:14pt">
45:  <tr><td colspan="2"><input type="button" class="butSt"
46:    style="background:#cccccc;color:#000000;width:200px;height:50px"
47:      onclick="resetPar()" value="Reset Parameters" /></td></tr>
48:  <tr><td colspan="2"><input type="button" class="butSt"
49:    style="background:#cccccc;color:#000000;width:200px;height:50px"
50:      onclick="txtContent()" value="Text Area Content" /></td></tr>
51: </table>
52: <div style="position:absolute;top:500px;left:30px;font-size:14pt"
53:   id="outMsg"></div>
54: </body>
55: <script src="ex10-10.js"></script>
56: </html>

This page contains a textarea (lines 1625) of 9 rows and each row has 60 characters. The initial content of the textarea is the text between the tag names. After the textarea, we have a table containing four select boxes (lines 2642) used to control the following properties of textarea:



Font color          Font size
Background color    Font family

An event handler onchange=changeCSS() is assigned to each select box so that whenever there is a change of selection, the changeCSS() function is called. This makes sure that the associated change is in real time. Two buttons are also defined in lines 4451 to reset the parameters of the select boxes and get the content of textarea. A screen shot of this page is shown in Fig. 10.16.

Figure 10.16. ex10-10.htm

graphics/10fig16.jpg


The program file for this example is ex10-10.js and is listed as follows:



Example: ex10-10.js - The ECMAScript For ex1010.htm

 1: sizeIndex = new Array(16,12,14,18)
 2: famIndex = new Array("Arial","Times")
 3: colIndex = new Array("#880000","#008800","#000088")
 4: bgIndex = new Array("#aaffaa","#ffaaaa","#aaaaff")
 5: function changeCSS()
 6: {
 7:   llSize = document.getElementById("sizeIdx").selectedIndex
 8:   llFam = document.getElementById("famIdx").selectedIndex
 9:   llCol = document.getElementById("colIdx").selectedIndex
10:   llBg = document.getElementById("bgIdx").selectedIndex
11:
12:   llV = document.getElementById("myTxtArea").style
13:   llV.fontSize = sizeIndex[llSize]+"pt"
14:   llV.color = colIndex[llCol]
15:   llV.fontFamily = famIndex[llFam]
16:   llV.background = bgIndex[llBg]
17: }
18:
19: function resetPar()
20: {
21:   document.getElementById("sizeIdx").selectedIndex= 0
22:   document.getElementById("colIdx").selectedIndex= 0
23:   document.getElementById("famIdx").selectedIndex= 0
24:   document.getElementById("bgIdx").selectedIndex= 0
25:   document.getElementById("outMsg").innerHTML= ""
26:
27:   llV = document.getElementById("myTxtArea").style
28:   llV.fontSize = "16pt"
29:   llV.color = "#880000"
30:   llV.fontFamily = "Arial"
31:   llV.background = "#aaffaa"
32: }
33:
34: function txtContent()
35: {
36:   llV = document.getElementById("myTxtArea")
37:   document.getElementById("outMsg").innerHTML=llV.value
38:
39: }

First, we use arrays to remember all the values for "Font Size," "Font Family," "Font Color," and "Background Color." These arrays are also used later to convert the selected option to the selection data. There is an event handler onchange="changeCSS()" installed for each of the select boxes, e.g., the first select box (lines 2830 of ex10.10.htm):



<select onchange="changeCSS()" id="colIdx" class="butSt">
   <option>#880000</option>
   <option>#008800</option>
   <option>#000088</option>
</select>

The function changeCSS() is called if any changes of the selection are detected. The event function changeCSS() defined in ex10-10.js gets all the selected values from the select boxes (lines 710 of ex10-10.js) and then assigns them to the CSS property of textarea. Since the assignment of CSS is a real-time process, the change is immediate.

If the Reset Parameters button is pressed, the resetPar() function (lines 1932) is called. This function first restores the selectedIndex of select boxes to 0 and then assigns the original value of the CSS properties back to textarea.

If the Text Area Content button is pressed, the function txtContent() gets the contents of textarea and displays the information to the output area specified in line 37. A screen shot of this in action is shown in Fig. 10.17.

Figure 10.17. Controlling text area and select boxes

graphics/10fig17.jpg


10.4.4 A page to change options at run time

In fact, both the IE and NS family of browsers allow you to change options inside a select element at run time. The basic format is simple. All you have to do is to change the firstChild.data property of the desired option. For example, the following statements can change the first option of the "holiday" select box to "My First Option":



llV = document.getElementById("holiday")
llV.options.item(0).firstChild.data = "My First Option"

As an application of this feature, we consider a page to give away some free gifts to customers. Suppose you have two kinds of free gifts, "Holiday Add On," and "Consumer Goods," and each catalog has its own items.

The user can pick one of the radio buttons representing the associated catalog and select the gift items from a select box. The changes on the select box are transparent to the user and are in real time.

The interface part of this example is



Example: ex10-11.htm - A Page To Change Options At Run Time

 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> .selSt{width:380px;height:35px;background:#aaffaa;
 6:  font-family:arial;font-weight:bold;font-size:16pt;color:#880000}</style>
 7:  <head><title> Change Options At Run Time -- ex1011.htm</title></head>
 8:  <body style="background:#000088;font-family:arial;font-size:22pt;
 9:       color:#ffff00;font-weight:bold;text-align:center"><br />
10:  Special Promotion From www.pwt-ex.com<br/>Claim Your Free Gift
11:     <br /><br />
12:  <form action="">
13:  <table style="position:absolute;top:160px;left:60px;text-align:left;
14:   font-size:18pt">
15:   <tr><td colspan="2">Select Your Free Gift Catalog Please</td></tr>
16:   <tr><td colspan="2">Holiday Add On</td>
17:     <td><input type="radio" id="gift" name="gift" checked
18:      onclick="chgCatalog(1)" class="selSt" style="width:40px" /></td></tr>
19:   <tr><td colspan="2">Consumer Goods</td>
20:     <td><input type="radio" id="gift" name="gift"
21:      onclick="chgCatalog(2)" class="selSt" style="width:40px" /></td></tr>
22:  </table>
23:  </form>
24:
25:  <div style="position:absolute;top:300px;left:60px;text-align:left;
26:          font-size:18pt">Your Free Gift<br />
27:    <select id="freeGift" name="freeGift" class="selSt">
28:     <option>Two Nights Hotel In London</option>
29:     <option>One Week Free Car Rental</option>
30:     <option>Free Travel Insurance</option>
31:     <option>Dinner For Two</option>
32:     <option>One Free Local Excursion</option>
33:   </select><br /><br /><br />
34:   <div id="outMsg"></div>
35:  </div>
36:  <input type="button" value="Order" onclick="orderGift()"
37:     style="position:absolute;top:305px;left:460px;width:100px;
38:     height:60px;font-family:arial;font-size:18pt;font-weight:bold" />
39: </body>
40: <script src="ex10-11.js"></script>
41: </html>
42:

This page contains two radio boxes and one select box. The radio boxes are defined inside the table in lines 1322. The select box is specified inside the division element in lines 2535. Initially, the first box, "Holiday Add On," is checked so that the select box contains the following options:

  • Two Nights Hotel in London

  • One Week Free Car Rental

  • Free Travel Insurance

  • Dinner For Two

  • One Free Local Excursion

Once the radio box "Consumer Goods" is clicked, the options list of the select box changes to the following list:

  • Digital DVD Playero

  • Digital Camera

  • Postscript Printer

  • DVD & RW Combo Drive

  • A Handheld Computer

When a selection is picked and the Order button is pressed, the selected option is displayed in the display area. Some screen shots of this example in action are shown in Figs 10.18 and 10.19.

Figure 10.18. ex10-11.htm

graphics/10fig18.jpg


Figure 10.19. Change options with radio boxes

graphics/10fig19.jpg


The driving force for this example is the program file ex10-11.js listed below.



Example: ex10-11.js - The ECMAScript For ex1011.htm

 1:  function chgCatalog(butV)
 2:  {
 3:   llV = document.getElementById("freeGift")
 4:   llV.length = 5
 5:   llV.selectedIndex = -1
 6:   if (butV ==1) {
 7:    llV.options.item(0).firstChild.data = "Two Nights Hotel in London"
 8:    llV.options.item(1).firstChild.data = "One Week Free Car Rental"
 9:    llV.options.item(2).firstChild.data = "Free Travel Insurance"
10:    llV.options.item(3).firstChild.data = "Dinner For Two"
11:    llV.options.item(4).firstChild.data = "One Free Local Excursion"
12:    llSt = "Pick Holiday Add On!"
13:   }
14:   if (butV ==2) {
15:    llV.options.item(0).firstChild.data = "Digital DVD Player"
16:    llV.options.item(1).firstChild.data = "Digital Camera"
17:    llV.options.item(2).firstChild.data = "Postscript Laser Printer"
18:    llV.options.item(3).firstChild.data = "DVD & RW Combo Drive"
19:    llV.options.item(4).firstChild.data = "A Handheld Computer"
20:    llSt = "Pick Your Consumer Goods!"
21:   }
22:   llV.selectedIndex =0
23:   document.getElementById("outMsg").innerHTML=llSt
24:  }
25:
26:  function orderGift()
27:  {
28:    llV = document.getElementById("freeGift")
29:    selectV = llV.selectedIndex
30:    llSt = "Your Free Gift Is: "+
31:           llV.options.item(selectV).firstChild.data
32:    document.getElementById("outMsg").innerHTML=llSt
33:  }

This program file is in fact quite easy to understand. When the first radio box "Holiday Add On" is pressed, the chgCatalog(butV) function is called with butV=1. Since the argument butV is 1, the statements in lines 711 are executed and the options of the select box are determined accordingly. When chgCatalog(2) is called, the similar statements in lines 1519 specify another new set of options for the select box. The "Pick Your Consumer Goods!" message is output to the display area at the end of this function.

When the user clicks the Order button, the function orderGift() is called. This function gets the selected item via the firstChild.data property in line 31 and outputs a message to the display area to indicate the selection.

10.4.5 Adding and deleting an option

A select box is similar to a drop-down menu. The options are mostly hidden from the user until the associated "arrow" button is clicked. In many cases this feature makes them an ideal tool to add or delete options (or items) at run time unnoticed. To allow the addition or deletion of elements on a page is another achievement of the W3C DOM. To understand this requires some knowledge of the DOM's tree and structure. However, the interface for the select element also provides two functions for you to add and delete options in an easy way. The prototypes of these two functions are



void add(element, before)
void remove(in long index)

One good way to demonstrate how to use them is by means of an example. For this purpose, we develop a page with a text field, two buttons, and one select box. The text field allows a user to type in a new option. When the Add Option button is clicked, the text will be added at the end of the select box as an additional option. When the Delete button is clicked, the option at the end of the select box will be deleted. Some screen shots of this example in action are shown in Figs 10.20 and 10.21.

Figure 10.20. ex10-12.htm

graphics/10fig20.jpg


Figure 10.21. Delete some options

graphics/10fig21.jpg


The construction of the text field, buttons, and select box is quite simple and is listed in the following page:



Example: ex10-12.htm - Adding & Deleting Options

 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:  .selSt{width:280px;height:35px;background:#aaffaa;
 7:   font-family:arial;font-weight:bold;font-size:18pt;color:#880000}
 8:  .butSt{width:120px;height:35px;background:#aaaaaa;
 9:   font-family:arial;font-weight:bold;font-size:14pt;color:#880000}
10: </style>
11: <head><title>Adding & Deleting Options -- ex1012.htm</title></head>
12: <body style="background:#000088;font-family:arial;font-size:22pt;
13:      color:#ffff00;font-weight:bold;text-align:center"><br />
14:   Adding & Deleting Options <br />In A Select Box<br /><br />
15:
16:  <input type="text" id="addId" class="selSt" />
17:  <input type="button" value="Add Option" class="butSt"
18:      onclick="addOption()"/><br /><br />
19:
20:  <select id="mySelectBox" name="mySelectBox" class="selSt">
21:    <option />First Option
22:    <option />Second Option
23:    <option />Third Option
24:    <option />Fourth Option
25:  </select>
26:  <input type="button" value="Delete" class="butSt" id="delId"
27:      onclick="delOption()" />
28:
29: </body>
30: <script src="ex10-12.js"></script>
31: </html>

A text field and a button are defined in lines 1617. If the Add Option button is clicked, the function addOption() is called to get the text and append it to the end of the select box. The select box is defined in lines 2024 with four options. Another button is created just after the select box. This button calls the function delOption() to delete the last option of the box. The addOption() and delOption() functions are specified in the file ex10-12.js.



Example: ex10-12.js - The ECMAScript For ex1012.htm

 1:  function addOption()
 2:  {
 3:
 4:   llV = document.getElementById("mySelectBox")
 5:   if ( llV.length < 10)
 6:   {
 7:    newoption = document.createElement("option")
 8:    newoption.text = document.getElementById("AddId").value
 9:    llV.add(newoption)
10:    llV1 = document.getElementById("delId")
11:    if (!llV1.disabled) llV1.disabled = false
12:   }
13:  }
14:
15:  function delOption()
16:  {
17:   llV = document.getElementById("mySelectBox")
18:   if (llV.length > 0)
19:   {
20:     llV.remove(llV.length-1)
21:   } else {
22:     document.getElementById("delId").disabled = true
23:   }
24:  }

To use the add() function, you need to create an element <option> and put some information into the newly created option. This is the job of the statements in lines 78:



newoption = document.createElement("option")
newoption.text = document.getElementById("AddId").value

These two statements produce the following result:



<option> .. Some Text From The Text Field .. </option>

Once you have this XHTML element stored in the newoption object, the add() function can be called to add the option to the select box. The statement in line 9



llV.add(newoption)

is equivalent to putting the <option> element at the end of the select box; llV is the object identity of the select box defined in line 4:



llV = document.getElementById("mySelectBox")

The following function call puts the option element in the third position of the select box:



llV.add(newoption,2)

Whenever the Add Option button is clicked, the text in the text field is added to the select box until there are 10 options in the box. The two statements in lines 1011 are used to detect whether the Delete button has been disabled since there are no more options in the box. If the button is disabled, the statement in line 11 turns it on again.

To delete an option in the select box is easy. All you have to do is to call the DOM function remove(). You first get the identity of the select box as shown in line 17 and then make the call



llV.remove(llV.length 1)

This statement removes the last option in the select box. If you keep pressing the Delete button, the options in the box will be deleted one by one until none is left and the button will be disabled. Now let's consider a practical example.

    Table of Contents

    Previous Next