Text-Related Form Objects (Chapter 25)

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

T he topic of button form controls encompasses clickable user interface elements that have a va rie ty of applica­

tions, some of w hich are quite specific. For example, radio buttons should be presented in groups offering tw o o r more m utually exclusive choices. A checkbox, on the other hand, is used to signify an “ on” o r “ off” setting related to whatever label is associated w ith the button. The only tric k y part of these special behaviors is tha t radio buttons assigned to a single group must share the same name, and the document object model provides access to single buttons w ith in the group by way of an array of objects tha t share the name. For a scrip t to determine w hich radio button is cu rre n tly selected, a for loop through the array then allows the scrip t to inspect the checked p ro p e rty of each button to find the one whose value is true.

Then there are w hat appear to be plain old rounded rectan­

gle buttons. Two versions — the INPUT element of type button and the newer BUTTON elem ent— w o rk v e ry much alike, although the la tte r is not obligated to appear nested inside a FORM element. A common mistake among newcomers, how­

ever, is to use the INPUT element of type submi t to behave as a button whose sole job is to trigger some scrip t function w ith o u t any form submission. Genuine subm it buttons force the form to subm it itself, even if the b u tto n ’s on Cl i ck event handler invokes a scrip t function. If the form has no ACTION a ttribu te assigned to it, then the default action of the submis­

sion causes the page to reload, probably destroying whatever tentative scrip t variable values and other data have been gathered on the page.

Examples Highlights

♦ If a b u tto n ’s event handler passes that button object’s reference to the handler function, the object’s form p ro p e rty provides the function w ith a valid reference to the containing form, allowing the scrip t an easy way to access inform ation about the form or create references to other form controls.

♦ ♦ ♦ ♦ In This C ha p te r Triggering action from a user's click of a button

Using checkboxes to control display of other form controls Distinguishing between radio button families and their individual buttons

♦ ♦ ♦ ♦

3 4 4 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Of course, the on Cl i ck event handler is the most im p o rta nt for button con­

trols. Listing 24-1 demonstrates passing button references to event handler functions.

♦ Listing 24-4 shows how a checkbox setting can influence the URL of the form ’s action.

♦ Sometimes a com plex form requires tha t checking a checkbox makes other items in the form visible. Listing 24-5 employs scriptable style sheets to assist in the job.

♦ Use Listing 24-6 as a model for how to find w hich radio button among those of a single group is checked.

The BUTTON Element Object and the Button, Submit, and Reset Input Objects

Properties

f o r m

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

C om pa tib ility / / / / / / / / /

Example

The follow ing function fragment receives a reference to a button element as the parameter. The button reference is needed to decide w hich branch to follow; then the form is subm itted.

function setAction(btn) { if (btn.name == "normal” ) {

btn.form.action = "cgi-bin/normal.pi"

) else if (btn.name ~ "special") {

btn.form.action = "cgi-bin/speci alHand!ing.pl"

1

btn. form. s u b m i t O }

Notice how this function doesn’t have to w o rry about the form reference,

because its job is to w o rk w ith whatever form encloses the button that triggers this function. Down in the form, tw o buttons invoke the same function. Only th e ir names ultim a tely determine the precise processing of the button click:

<F0RM>

< INPUT TYPE="button" NAME="normal" VALUE="Regular Handling"

onClick="setAction(thi s ) ">

document Jorm Object.buttonObject.form

Chapter 8 ♦ Button Objects (Chapter 24) 3 4 5

<INPUT TYPE="button" NAME="speci a l " VALUE="Special Handling"

onClick="setAction(thi s ) ">

</F0RM>

name

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

C om pa tib ility / / / /

Example

See the example fo r the form p ro p e rty earlier in this chapter for a practical application of the name property.

val ue

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

C om pa tib ility / / / / / /

Example

In the follow ing excerpt, the statement toggles the label of a button from “ Play”

to “Stop” (except in NN/Mac through version 4):

var btn = document.forms[0].cortrolButton

btn.value = (btn.value == "Play") ? "Stop" : "Play"

Methods

cli ck()

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

C om pa tib ility / / / /

Example

The follow ing statement demonstrates how to scrip t a click action on a button form control named sender:

document.forms[0].sender.cl ick()

document.formObject.buttonObject.clickQ

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

Event handlers

onCli ck

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

C om pa tib ility / / / / / / / / /

Example

Listing 24-1 demonstrates not only the on Cl i ck event handler of a button but also how you may need to extract a particula r b u tto n ’s name o r va l ue properties from a general-purpose function th a t services m ultiple buttons. In this case, each button passes its own object as a parameter to the d i spl a y T e a m () function. The function then displays the results in an alert dialog box. A real-world application would probably use a more complex i f . . . e 1 s e decision tree to perform more sophisticated actions based on the button clicked (o r use a swi tc h construction on the b t n . va 1 ue expression for NN4+ and IE4+).

Listing 24-1 : Three Buttons sharing One Function

<HTML>

<HEAD>

<TITLE>Button Click</TITLE>

<scRIPT LANGUAGE“ '1 J a v a S c r i p t ”>

function displayTeam(btn) { if (btn.value == "A bbott” ) if (btn.value — "Rowan") if (btn.value == "Martin” )

}

</SC RIPT>

</HEAD>

{alertC'Abbott {alertC'Rowan &

(alertC'Martin

& C o s t e l l o ” )) Martin")}

& Lewis")}

<B0DY>

Click on your favorite half of a popular comedy team:<p>

<F0RM>

< INPUT TYPE="button" VA LU E="Abtott’

< INPUT TYPE="button" VALUE“ "Rowan"

< INPUT TYPE="button" VA LU E="Martin’

</F0RM>

</B0DY>

</HTML>

onClick=''displayTeam(this)">

onClick='’displayTeani(this)">

onCli c k = ”di s p la yT ea m( th is )">

document JormObject.buttonObject.onCUck

Checkbox Input Object

Chapter 8 ♦ Button Objects (Chapter 24)

Properties

checked

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

C om pa tib ility ✓ ✓ ✓ ✓ ✓ ✓ / / /

Example

The simple example in Listing 24-2 passes a form object reference to the JavaScript function. The function, in turn, reads the c h e c k e d value of the form ’s checkbox object ( c h e c k T h i s . c h e c k e d ) and uses its Boolean value as the test result for the i f .. . e 1 s e construction.

Listing 24-2: The checked Property as a Conditional

<HTML>

<HEAD>

<TITLE>Checkbox Inspector</TITLE>

<SCRIPT LANGUAGE“ "JavaScript”>

function inspectBox(form) ( if (form.checkThis.checked) {

alertC'The box is checked.") ) else (

alertC'The box is not checked at the moment.") )

}

</SC RIPT>

</HEAD>

<B0DY>

<F0RM>

< INPUT TYPE="checkbox" NAME="checkThis">Check here<P>

< INPUT TYPE="button" NAME="boxChecker" VALUE="Inspect Box”

onClick="inspectBox(this.form)">

</F0RM>

</B0DY>

</HTML>

3 4 7

docum ent.formObjectcheckboxObject.checked

defaultChecked

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

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

Compatibility y y y y y y y y y

Example

The function in Listing 24-3 (this fragment is not in the CD-ROM listings) is designed to compare the current setting of a checkbox against its default value. The i f construction compares the current status of the box against its default status.

Both are Boolean values, so they can be compared against each other. If the current and default settings don’t match, the function goes on to handle the case in w hich the current setting is other than the default.

Listing 24-3: Examining the defaultChecked Property

function compareBrowser(thisBox) {

if (thisBox.checked != thisBox.defaultChecked) {

/ / statements about using a d i f f e r e n t set of HTML pages 1

val ue

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

C om pa tib ility s s s

/ / / /

Example

The scenario for the skeleton HTML page in Listing 24-4 is a form w ith a check­

box whose selection determines w hich of tw o actions to follow for submission to the server. A fter the user clicks the Submit button, a JavaScript function examines the checkbox’s checked property. If the p ro p e rty is true (the button is checked), the scrip t sets the acti on p roperty for the entire form to the content of the value p ro p e rty — thus influencing where the form goes on the server side. If you tr y this listing on yo ur computer, the result you see varies w idely w ith the browser version you use. For most browsers, you see some indication (an e rro r alert o r other screen notation) th a t a file w ith the name p r i m a ryLIRL or al ternatellRL doesn’t exist.

Unfortunately, IE5.5/Windows does not display the name of the file that can’t be opened. T ry the example in another browser if you have one. The names and the erro r message come from the submission process fo r this demonstration.

document JormObject.checkboxObject.va\ue

Chapter 8 ♦ Button Objects (Chapter 24) 3 4 9

Listing 24-4: Adjusting a CGI Submission Action

<HTML>

<HEAD>

<TITLE>Checkbox Submi ssi on</TITLE>

<SCRIPT LANGUAGE“ "JavaScript”>

function setAction(form) {

if (form.checkThis.checked) {

form.action = form.checkThis.value ) else {

form.action = "file://primaryURL"

)

return true }

</SC RIPT>

</HEAD>

<B0DY>

<F0RM METHOD“ "POST" ACTI0N“ "">

< INPUT TYPE“ "checkbox" NAME="checkThis" VALUE="fi1e://alternateUR.">Use alternate<P>

< INPUT TYPE="submit" NAME="boxChecker" onClick="return setAction(this.form)">

</F0RM>

</B0DY>

</HTML>

Event handlers

onCli ck

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

C om pa tib ility / / / / /

Example

The page in Listing 24-5 shows how to tra p the click event in one checkbox to influence the v is ib ility and display of other form controls. A fter you turn on the M onitor checkbox, a list of radio buttons for m o n itor sizes appears. Similarly, engaging the Communications checkbox makes tw o radio buttons visible. Your choice of radio button brings up one of tw o fu rth e r choices w ith in the same table cell (see Figure 8-1).

document.formObject.checkboxObject.onCl\ck

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

'3 C heckbux Event H d i u i l e i M iciu su ft In ternet E xp luiei Eile E dit V ie w F avorites I o o ls Help

ô - J $ a ầỡ J

Udck T o w a rd S to p R e fre s h Hom e S e a rc h Favorites History ü Mail Check all accessories fo r your computer: ~ 3

r* M onitor

w Communications

j (•"^Modern c N etw o rk

<“■ < 5 6 k b p s 56kbps c IS D N (any speed) c Cable

M y C om puter Done

Figure 8 -1: Clicking on button choices reveals additional relevant choices

Notice how the t o g g l e ( ) function was w ritte n as a generalizable function. This function can accept a reference to any checkbox object and any related span. If five more groups like this were added to the table, no additional functions w ould be needed.

In the s w a p ( ) function, an application of a nested i f ... el se shortcut construc­

tio n is used to convert the Boolean values of the checked p ro pe rty to the strings needed for the di spl ay style property. The nesting is used to allow a single state­

ment to take care of tw o conditions: the group of buttons to be controlled and the checked p ro pe rty of the button invoking the function. This function is not general­

izable, because it contains explicit references to objects in the document. The s w a p ( ) function can be made generalizable, but due to the special relationships between pairs of span elements (meaning one has to be hidden while the other dis­

played in its place), the function would require more parameters to fill in the blanks where explicit references are needed.

Note A rendering bug in NN6 causes the form controls in the lower right frame to lose their settings when the elements have their d i spl ay style property set to none.

The problem is related to the inclusion of P or similar block elements inside a table cell that contains controls. Therefore, if you uncheck and recheck the Communications checkbox in the example page, the previously displayed sub­

group shows up even though no radio buttons are selected. You can script around this bug by preserving radio button settings in a global variable as you hide the group, and restoring the settings when you show the group again.

docum ent Jorm Object.checkboxObject.onCiick

Chapter 8 ♦ Button Objects (Chapter 24) 3 5 1

Syntax used to address elements here is the W3C DOM-compatible form, so this listing runs as is w ith IE5+ and NN6+. You can m odify the listing to run in IE4 by adapting references to the document .all format.

Listing 24-5: A Checkbox and an onClick event Handler

Handler</TITLE>

">

: h i dden}

:h i dden}

<HTML>

<HEAD>

<TITLE>Checkbox Event

<STYLE TYPE="text/css"

#monGroup (visibility:

#comGroup {visibility:

</STYLE>

<SCRIPT LANGUAGE“ "JavaScript”>

// toggle visibility of a main group spans function toggle(chkbox, group) (

var visSetting = (chkbox.checked) ? "visible" : "hidden"

document.getElementByld(grcup).style.visibi1ity = visSetting }

// swap display of communications sub group spans function swap(radBtn, group) {

var modemsVisSetting = (group ((radBtn.checked)

var netwksVisSetting = (group ((radBtn.checked)

document.getElementById("modems").style.di splay document.getElementById( "netwks").style.display )

</SC RIPT>

</HEAD>

"modems”) ?

"none") : "none"

"netwks") ?

"none") : "none"

modemsVi sSetti ng netwksVi sSetti ng

<B0DY>

<F0RM>

<H3>Check all accessories for your computer:</H3>

<TABLE B0RDER=2 CELLPADDING=5>

<TR>

<TD>

< INPUT TYPE="checkbox onClick="toggle(this,

</TD>

<TD>

<SPAN ID="monGroup">

< INPUT TYPE="radio" NAME=

< INPUT TYPE="radio" NAME=

radio" NAME=

radio" NAME=

1 NAME="monitor"

'monGroup')">Monitor

< INPUT TYPE

< INPUT TYPE

</SPAN>

</TD>

</TR>

<TR>

<TD>

moni torType">15"

moni torType">17"

monitorType">21"

monitorType"ằ21"

Continued

document.formObject.checkboxObject.onClick

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

Listing 24-5 (continued)

< INPUT TYPE="checkbox" NAME="comms"

onCli ck=''toggle(this, 'comGroup')">Communi cati ons

</TD>

<TD>

<SPAN ID="comGroup">

< P X I N P U T TYPE="radio" NAME="commType"

onClick="swap(this, 'modems')">Modem

< INPUT TYPE="radi o" NAKE-'commType”

onClick="swap(this, 'netwks')”>Network</P>

< P X S P A N ID= "modems'' STYLE="display:none">

< INPUT TYPE="radio" NAME="modemType"X56kbps

< INPUT TYPE="radio" NAME="modemType">56kbps

< INPUT TYPE="radio" NAME="modemType">ISDN (any speed)

< INPUT TYPE="radio" NAME="modemType">Cable

</SPAN>

<SPAN ID="netwks" STYLE="display:none">

< INPUT TYPE="radio" NAME="netwkType">Ethernet 10Mbps (10-Base T)

< INPUT TYPE="radio" NAME="netwkType">Ethernet lOOHbps (10/100)

< INPUT TYPE="radio" NAME="netwkType">Tl or greater

</SPAN>&nbsp;</P>

</S PAN >

</TD>

</TR>

</TABLE>

</F0RM>

</B0DY>

</HTML>

Radio Input Object

Properties

checked

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

C om pa tib ility y y y y y y y y y

Example

Listing 24-6 uses a repeat loop in a function to look through all buttons in the Stooges group in search of the checked button. A fter the loop finds the one whose

document Jorm Object.radioObject.checked

Chapter 8 ♦ Button Objects (Chapter 24) 3 5 3

checked p ro pe rty is t r u e , it returns the value of the index. In one instance, that index value is used to extract the v a l u e p ro p e rty for display in the alert dialog box;

in the other instance, the value helps determine w hich button in the group is next in line to have its checked p roperty set to t r u e .

Listing 24-6: Finding the Selected Button in a Radio Group

<HTML>

<HEAD>

<TITLE>Extracting Highlighted Radio ESutton</TITLE>

<SCRIPT LANGUAGE“ "JavaScript">

function getSelectedButton(buttonGroup){

for (var i - 0; i < buttonGroup.length; i++) ( if (buttonGroup[i].checked) (

return i )

1 return 0 )

function full Name(form) (

var i = getSelectedButton(form.stooges)

alertC'You chose " + form.stooges[i].value + ".") )

function cycle(form) (

var i = getSelectedButton(form.stooges) if (1+1 == form.stooges.lergth) (

form.stooges[0].checked = true ) else {

form.stooges[i+l].checked = true 1

1

</SCRIPT>

</HEAD>

<B0DY>

<F0RM>

<B>Select your favorite Stooge:</B>

< P X I N P U T TYPE=''radio" NAME="stooges" VALUE=”Moe Howard" CHECKED>Hoe

< INPUT TYPE=”radio" NAME="stooces" VALUE="Larry Fine" >Larry

< INPUT TYPE="radio" NAME="stooces” VALUE="Curly Howard" >Curly

< INPUT TYPE="radio" NAME="stooces" VALUE="Shemp Howard" >Shemp</P>

< P X I N P U T TYPE-"button" NAME="Viewer" VALUE="View Full Name..."

onCl ick="ful 1 Name( thi s . f orm)"X/P>

< P X I N P U T TYPE="button" NAME="Cyc1er" VALUE=”Cycle Buttons"

onClick="cycle(this.form)"> </F>

</F0RM>

</B0DY>

</HTML>

document.formObject.radioObject.checked

defaultChecked

3 5 4 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

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

Compatibility y y y y y y y y y

Example

In the scrip t fragment of Listing 24-7 (not among the CD-ROM files), a function is passed a reference to a form containing the Stooges radio buttons. The goal is to see, in as general a way as possible (supplying the radio group name where

needed), if the user changed the default setting. Looping through each of the radio buttons, you look fo r the one whose CHECKED a ttribu te is set in the <INPUT> defini­

tion. W ith that index value ( i ) in hand, you then look to see if that entry is s till checked. If not (notice the ! negation operator), you display an alert dialog box about the change.

Listing 24-7: Has a Radio Button Changed?

function groupChanged(form) {

for (var i = 0; i < form.stooges.length; i++) ( if (form.stooges[i].defaultChecked) (

if ( !form.stooges[i].checked) {

alert("This radio group has been changed.") }

) ) }

1ength

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

C om pa tib ility / / / /

Example

See the loop construction w ith in the function of Listing 24-7 fo r one way to apply the 1 eriy Lh property.

document Jorm Object.radioObjectAength

Chapter 8 ♦ Button Objects (Chapter 24)

val ue

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

C om pa tib ility / / / / / / / / /

Example

Listing 24-6 (earlier in this chapter) demonstrates how a function extracts the val ue p ro p e rty of a radio button to display otherwise hidden inform ation stored w ith a button. In this case, it lets the alert dialog box show the fu ll name of the selected Stooge.

Event handlers

onCli ck

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

C om pa tib ility / / / / / / / / /

Example

Every tim e a user clicks one of the radio buttons in Listing 24-8, he o r she sets a global variable to true o r f al se, depending on w hether the person is a Shemp lover. This action is independent of the action that is taking place if the user clicks on the View Full Name button. An onllnl oad event handler in the <B0DY> definition triggers a function tha t displays a message to Shemp lovers ju st before the page clears (click the brow ser’s Reload button to leave the current page p rio r to reload­

ing). Here I use an initialize function triggered by on Load so that the current radio button selection sets the global value upon a reload.

Listing 24-8: An onClick event Handler fo r Radio Buttons

<HTML>

<HEAD>

<TITLE>Radio Button onClick Hardler</TITLE>

<SCRIPT LANGUAGE“ ”JavaScript”>

var ShempOPhile - false function initValueO (

ShempOPhile = document.forms[0],stooges[3].checked )

function ful1 Name(form) {

for (var i = 0; i < form.stooges.length; i++) { if (form.stooges[i].checked) (

break

Continued

3 5 5

document.formObject.radioObject.onChck

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

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

(631 trang)