Table and List Objects (Chapter 2 7 )

Một phần của tài liệu tài liệu hướng dẫn sử dụng javascript (Trang 468 - 480)

T he SELECT element is the best space-saving device in the HTML form repertoire. W hether you choose the pop-up menu o r scrolling lis t display style, your page can provide vis­

ito rs w ith a visually compact list of lite ra lly hundreds of items from w hich to choose. From a scrip te r’s p oint of view, how­

ever, it is a complex item to manage, especially in older browsers.

In tru th , the SELECT element is an outer w rapper fo r the OPTION element items nested w ithin. Each OPTION element contains the te xt tha t the user sees in the list, as w ell as a h id ­ den value that may be more meaningful to a server database or client script. The d iffic u lty w ith browsers p rio r to IE4 and NN6 is tha t reading the hidden value of the cu rre n tly chosen item in the lis t requires an extensive reference to not only the SELECT element, but to the item in the array of OPTION ele­

ment objects. To reach th a t specific item, the scrip t uses a ref­

erence to the SELECT object’s s e l e c t e d l n d e x p ro p e rty as the o p t i o n s array index. Newer browsers sim p lify the m atter by providing a single v a l u e p roperty fo r the SELECT object that returns the value of the currently selected item (o r of the firs t item when m ultiple choices are allowed).

Many browser versions provide scrip t facilities for m odify­

ing the content of a SELECT list. But the effect is not perfect in browsers th a t don’t also reflow the page to reflect the poten­

tia lly resized w id th of the list.

A user interface debate rages about w hether a SELECT list, whose purpose is obviously intended to direct site navigation, should navigate im m ediately upon making a choice o r if the user should also click on an explicit “ Go” button next to the list. The form er is faster fo r the im patient visitor, but the lat­

te r doesn’t shoot off to an undesired page when the user makes a wrong selection. Good luck w ith tha t decision.

♦ ♦ ♦ ♦

In This Chapter

Triggering action based on a user's selection in a pop-up or select list

Reading hidden and visible values of OPTION element items

Scripting SELECT objects that allow multiple selections

3 7 0 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Examples Highlights

♦ To harvest the values of all selected items in a m ultiple list, your scrip t needs to cycle through the SELECT element’s o p t i o n s array and inspect the

sel e c t e d p ro p e rty of each, as shown in Listing 26-4.

♦ Scripts can also retrieve the text of the selected item, instead of the hidden value. Compare tw o sim ilar applications tha t w ork w ith the t e x t (Listing 26-5) and v a l ue (L is tin g 26-6) properties.

♦ Listings 26-5 and 26-6 show the backward-compatible, long reference to retrieve a chosen o ptio n ’s details. The modern alternative accompanies the example for the S E L E C T . v a l u e property.

♦ See Listing 26-8 for another example of triggering a scrip t via the o n C h a n g e

event handler of a SELECT object.

♦ Im plementations of the OPTGROUP element object may need improvement before Listing 26-9 behaves as it should to m odify hierarchical labels w ith in a SELECT list.

SELECT Element Object

Properties

1ength

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility / / / / / / / / /

Example

See Listing 26-1 in Chapter 26 of the JavaScript Bible for an illustra tio n of the way you use the l e n g t h p ro p e rty to help determine how often to cycle through the repeat loop in search of selected items. Because the loop counter, i , must start at 0, the counting continues u n til the loop counter is one less than the actual length value (w hich starts its count w ith 1).

multipie

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility y y y y

Example

The follow ing statement toggles between single and m ultiple selections on a SELECT element object whose SIZE a ttribu te is set to a value greater than 1:

SELECT.multiple

document.forms[0].mySelect.multi pie = !document.forms[0].mySelect.multi pie

opti ons[ index ]

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility / / / / / / / / /

Chapter 10 ♦ Select, Option, and Optgroup Objects (Chapter 26)

Example

See Listings 26-1 through 26-3 in Chapter 26 of the JavaScript Bible for examples of how the opti ons array references inform ation about the options inside a SELECT element.

opti ons[ index ] .defaul tSel ected

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility / / / / / / / / /

Example

The follow ing statement preserves a Boolean value if the firs t option of the SELECT list is the default selected item:

var zeroIsDefault = document.fcrms[0].1istName.options[0].defaultSelected

opti ons[ index ].i ndex

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility ✓ ✓ ✓ ✓ / / ✓ / /

Example

The follow ing statement assigns the index integer of the firs t option of a SELECT element named 1 i stName to a variable named i temlndex.

var itemlndex = document.forms[0].1istName.options[0].index

opti ons[ index ].sel ected

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility / / / / / / / / /

3 7 1

SELECT.options[in</ex].selected

3 7 2 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Example

To accumulate a lis t of all items selected by the user, the see Li s t ( ) function in Listing 26-4 system atically examines the o p t i ons [ i n d e x ] . sel ected p roperty of each item in the list. The text of each item whose sel e cted p roperty is t r u e is appended to the list. I add the " \ n " inline carriage returns and spaces to make the list in the alert dialog box look nice and indented. If you assign other values to the VALUE attributes of each option, the scrip t can extract the o p t i ons [ i n d e x ] . val ue p ro p e rty to collect those values instead.

Listing 26-4: Cycling through a Multiple-Selection List

<HTML>

<HEAD>

<TITLE>Accessories List</TITLE>

<SCRIPT LANGUAGE“ "JavaScript">

function seeList(form) { var result = ""

for (var i = 0; i < form.accList.length; i++) { if (form.accList.optiors[i] .selected) (

result += "\n " + form.accList.opti ons[i].text )

}

alert(”You have selected:" + result) }

</SC RIPT>

</HEAD>

<B0DY>

<F0RM>

<P>Control/Command-click on all accessories you use:

<SELECT NAME="accList" SIZE=9 MULTIPLE)

<0PTI0N SELECTED>Color Monitor

<0PTI0N>Modem

<0PTI0N>Scanner

<0PTI0N>Laser Printer

<0PTI0N>Tape Backup

<0PTI0N>M0 Drive

<0PTI0N>Video Camera

</SELECT> </P>

< P X I N P U T TYPE="button" VALUE="View Summary..."

onCl ick="seeList(thi s . form)”X / P >

</F0RM>

</B0DY>

</HTML>

SELECT.options[/n</ex].selected

Chapter 10 ♦ Select, Option, and Optgroup Objects (Chapter 26) 3 7 3

opti ons[ index ].text

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility / / / / / / / / /

Example

To demonstrate the t e x t p roperty of an option, Listing 26-5 applies the text from a selected option to the document. bgCol o r p ro p e rty of a document in the current window. The color names are part of the collection b u ilt into all scriptable

browsers; fortunately, the values are case-insensitive so tha t you can capitalize the c olor names displayed and assign them to the property.

Listing 26-5: Using the options[index].text Property

<HTML>

<HEAD>

<TITLE>Color Changer 1</TITLE>

<SCRIPT LANGUAGE“ "JavaScript'^

function seeColor(form) {

var newColor = (form.colorsList.options[form.colorsList.selectedIndex].text) document.bgColor = newColor

}

</SCRIPT>

</HEAD>

<B0DY>

<F0RM>

<P>Choose a background color:

<SELECT NAME="colorsList">

<0PTI0N SELECTED>Gray

<0PTI0N>Lime

<0PTI0N>Ivory

<0PTI0N>Red

< / S E L E C T X / P >

< P X I N P U T TYPE="button" VALUE="Change It" onCl i ck="seeCol or(thi s . form) " X / P >

</F0RM>

</B0DY>

</HTML>

SELECT.options[/f></ex].text

374 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

opti o n s [ index ] . v a l ue

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 1E5.5

Compatibility y y y y y y y y y

Example

Listing 26-6 requires the option text that the user sees to be in familiar, m ultiple- w ord form. But to set the color using the brow ser’s built-in color palette, you must use the one-word form. Those one-word values are stored in the VALUE attributes of each <0PTI0N> definition. The function then reads the val ue property, assigning it to the bgColor of the current document. If you prefer to use the hexadecimal trip le t form of color specifications, those values are assigned to the VALUE attributes (<0PT I ON VALUE="#e9967a" >Da r k Salmon).

Listing 26-6: Using the options[index].value Property

<HTML>

<HEAD>

<TITLE>Co1 or Changer 2</TITLE>

<SCRIPT LANGUAGE“ "JavaScript">

function seeColor(form) ( var newColor =

(form.colorsLi st.opti ons[form.colorsLi s t .s el ec te dI nd ex ].value) document.bgColor = newColor

}

</SCRIPT>

</HEAD>

<B0DY>

<F0RM>

<P>Choose a background color:

<SELECT NAME="colorsList">

<0PTI0N SELECTED VALUE="cornflowerblue">Cornflower Blue

<0PTI0N V A L U E = ”darksalmon">Dark Salmon

<0PTI0N VA LU E= "1ightgoldenrodyellow”>Light Goldenrod Yellow

<0PTION VALUE="seagreen">Sea Green

< / S E L E C T X / P >

< P X I N P U T TYPE="button" VALUE="Change It” onCl i ck="seeCol or(thi s . form) " X / P >

</F0RM>

</B0DY>

</HTML>

SELECT.options[/n</ex].value

Chapter 10 ♦ Select, Option, and Optgroup Objects (Chapter 26)

selectedlndex

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility / / / / / / / / /

Example

In the i n s p e c t ( ) function of Listing 26-7, notice that the value inside the opti ons p ro p e rty index brackets is a reference to the object’s sel ectedlndex property. Because this p ro p e rty always returns an integer value, it fulfills the needs of the index value fo r the opti ons property. Therefore, if you select Green in the pop-up menu, fo rm. col orsList. sel ected Index returns avalué of 1; that reduces the rest of the reference to form, col orsL1 s t . opti o n s [ l ] . text, w hich equals “Green.”

Listing 26-7: Using the selectedlndex Property

<HTML>

<HEAD>

<TITLE>Select Inspector</TITLE>

<SCRIPT LANGUAGE“ "JavaScript">

function inspect(form) {

alert(form.colorsList.options[form.colorsList.selectedIndex].text) )

</SCRIPT>

</HEAD>

<B0DY>

<F0RM>

< P X S E L E C T NAME="colorsList">

<0PTI0N SELECTED>Red

<0PT I ON VALUE= "PI ants"XI>Green</I>

<0PTI0N>B1ue

</SELECTX/P>

< P X I N P U T TYPE=”button" VALUE="Show Selection" onClick="inspect(this.form)"X/P>

</F0RM>

</B0DY>

</HTML>

3 7 5

SELECT.selectedlndex

si ze

3 7 6 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility / / / /

Example

The follow ing statement sets the num ber of visible items to 5:

document.forms[0].mySelect.size = 5

val ue

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility / / / /

Example

The function in Listing 26-6 that accesses the chosen value the long way can be sim plified for newer browsers only w ith the follow ing construction:

function seeColor(form) {

document.bgColor = form.colorsList.value }

Methods

i tem( index )

namedItern(" option ID” )

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility ✓

Example

The follow ing statement assigns an OPTION element reference to a variable:

var oneOption = document.forms[0].mySelect.namedItem("option3_2")

SELECT.itemQ

Chapter 10 ♦ Select, Option, and Optgroup Objects (Chapter 26) 3 7 7

Event handlers

onChange

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility / / / / / / / / /

Example

Listing 26-8 is a version of Listing 26-6 tha t invokes all action as the result of a user making a selection from the pop-up menu. The onChange event handler in the

<SELECT> tag replaces the action button. For this a p p lica tio n — when you desire a direct response to user in p u t— an appropriate method is to have the action trig ­ gered from the pop-up menu rather than by a separate action button.

Notice tw o other im portant changes. First, the SELECT element now contains a blank firs t option. When a user visits the page, nothing is selected yet, so you should present a blank option to encourage the user to make a selection. The func­

tio n also makes sure th a t the user selects one of the color-valued items before it attempts to change the background color.

Second, the BODY element contains an on Uni oad event handler that resets the form. The purpose behind this is tha t if the user navigates to another page and uses the Back button to return to the page, the script-adjusted background color does not persist. I recommend you return the SELECT element to its original setting.

Unfortunately, the reset does not stick to the form in IE4 and IE5 fo r Windows (although this problem appears to be repaired in IE5.5). Another way to approach this issue is to use the on Load event handler to invoke seeCol or ( ) , passing as a parameter a reference to the SELECT element. Thus, if the SELECT element choice persists, the background color is adjusted accordingly after the page loads.

Listing 26-8: Triggering a Color Change from a Pop-Up Menu

<HTML>

<HEAD>

<TITLE>Co1 or Changer 2</TITLE>

<SCRIPT LANGUAGE“ "JavaScript">

function seeColor(list) {

var newColor = (list.optiors[list.selectedIndex].value) if (newColor) (

document.bgColor = newColor }

}

</SC RIPT>

</HEAD>

<B0DY onUnload="document.forms[0].reset()”>

<F0RM>

Continued

SELECT.onChange

3 7 8 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Listing 26-8 (continued)

<P>Choose a background color:

<SELECT NAME="colorsList" onChange="seeColor(this)">

<0PTI ON SELECTED VALUE="”>

<0PTI0N VALUE="cornflowerblue">Cornf1ower Blue

<0PTI0N VALUE="darksalmon">Dark Salmon

<0PTI0N VALUE="lightgoldenrodyellow">Light Goldenrod Yellow

<0PTION VALUE="seagreen”>Sea Green

</SELECTX/P>

</F0RM>

</B0DY>

</HTML>

OPTION Element Object

Properties

label

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility ✓ ✓

Example

The follow ing statement modifies the text tha t appears as the selected text in a pop-up list:

document.forms[0].mySelect.options[3].1abel - "Widget 9000"

If this option is the cu rre n tly selected one, the text on the pop-up list at rest changes to the new label.

OPTGROUP Element Object

Properties

label

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility ✓ ✓

OPTCROUP.Iabel

Chapter 10 ♦ Select, Option, and Optgroup Objects (Chapter 26) 3 7 9

Example

I present Listing 26-9 in the hope tha t M icrosoft and Netscape w ill eventually eradicate the bugs that afflict the ir current im plem entations of the l a b e l property.

When the feature works as intended, Listing 26-9 demonstrates how a scrip t can alter the text of option group labels. This page is an enhanced version of the back­

ground color setters used in other examples of this chapter. Be aware that IE5/Mac does not alter the last OPTGROUP element’s label, and NN6 achieves only a partial change to the text displayed in the SELECT element.

Listing 26-9: Modifying OPTGROUP Element Labels

<HTML>

<HEAD>

<TITLE>Color Changer 3</TITLE>

<SCRIPT LANGUAGE“ "JavaScript">

var regularLabels = ["Reds","Greens","B1 ues”]

var natural Labels = ["Apples” ,"Leaves","Sea”]

function setRegularLabels(list) {

var optGrps = 1ist.getElementsByTagNamei"OPTGROUP") for (var i - 0; i < optGrps.length; i++) (

optGrps[i].1abel = regilarLabels[i]

) }

function setNaturalLabels(list) (

var optGrps = list.getElementsByTagNameC'OPTGROUP") for (var i = 0; i < optGrps.length; i++) {

optGrps[i].label = natural Labels[i]

) }

function seeColor(1ist) {

var newColor = (list.optiors[list.selectedIndex].value) if (newColor) (

document.bgColor = newColor 1

)

</SCRIPT>

</HEAD>

<B0DY onUnload="document.forms[0].reset()”>

<F0RM>

<P>Choose a background color:

<SELECT name="colorsList" onChange="seeColor(this)">

<0PTGR0UP ID=”optGrpl" label="Reds”>

<0PTI0N value="#ff9999">Light Red

<OPTION value=”#ff3366">Medium Red

<0PTI0N value="#ff0000”>Bright Red C0PTI0N value="#660000">Dark Red

</0PTGR0UP>

<0PTGR0UP ID="optGrp2" 1abel="Greens">

<OPTION value="#ccff66">Light Green

Continued

OPTGROUP.Iabel

3 8 0 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Listing 26-9 (continued)

COPTION val ue="#99ff33">Medium Green

<OPTION val ue="#OOffOO">Bright Green

<OPTION value="#006600">Dark Green

</OPTGROUP>

<OPTGROUP ID="optGrp3" 1abel=”B1ues">

<OPTION value="#ccffff">Light Blue

<OPTION val ue=''#66ccff''>Medium Blue

<OPTION value="#0000ff">Bright Blue

<0PTION value="#000066">Dark Blue

</0PTGR0UP>

</SELECTX/P>

<P>

< INPUT TYPE="radio" NAHE=”1abels" CHECKED

onClick=”setRegularLabels(this.form.colorsList)">Regular Label Names

< INPUT TYPE=''radio" NAHE="labels"

onCl ick=''setNatural Label s(thi s .form, col orsLi st) ">Label Names from Nature</P>

</FORM>

</BODY>

</HTML>

♦ ♦ ♦

OPTCROUP.Iabel

Table and

Một phần của tài liệu tài liệu hướng dẫn sử dụng javascript (Trang 468 - 480)

Tải bản đầy đủ (PDF)

(631 trang)