1. Trang chủ
  2. » Công Nghệ Thông Tin

JavaScript Bible, Gold Edition part 71 potx

10 276 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 158,47 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

An acceptable value is a full reference to a form control element INPUT, TEXTAREA, or SELECT element objects.. Button ObjectsThis chapter is devoted to those lovable buttons that invite

Trang 1

548 Part III ✦ Document Objects Reference

<FORM >

<FIELDSET ID=”form1set1”>

<LEGEND ID=”form1set1legend”>Choose the Desired Performance</LEGEND>

<INPUT TYPE=”radio” NAME=”speed” ID=”speed1”>

<LABEL FOR=”speed1”>Fastest (lower quality)</LABEL><BR>

<INPUT TYPE=”radio” NAME=”speed” ID=”speed2”>

<LABEL FOR=”speed2”>Slower (best quality)</LABEL>

</FIELDSET>

</FORM>

Even so, a LABEL and its associated form control element do not have to be adja-cent to each other in the source code For example, you can have a label in one cell

of a table row with the form control in another cell (in the same or different row)

Properties htmlFor

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

The htmlForproperty is the scripted equivalent of the FORattribute of the LABEL element An acceptable value is a full reference to a form control element (INPUT, TEXTAREA, or SELECT element objects) It is highly unlikely that you would modify this property for an existing LABEL element However, if your script is creating a new LABEL element (perhaps a replacement form), use this property to associate the label with a form control

Example on the CD-ROM

On the

CD-ROM

LABEL.htmlFor

Trang 2

Button Objects

This chapter is devoted to those lovable buttons that

invite users to initiate action and make choices with a

single click of the mouse button In this category fall the

stan-dard system-looking buttons with labels on them, as well as

radio buttons and checkboxes For such workhorses of the

HTML form, these objects have a limited vocabulary of

object-specific properties, methods, and event handlers

I group together the button, submit, and reset objects for

an important reason: They look alike yet they are intended for

very different purposes Knowing when to use which button is

important — especially when to differentiate between the

but-ton and submit objects Many a newcomer get the two

con-fused and wind up with scripting error headaches That

confusion won’t happen to you by the time you finish this

chapter

The BUTTON Element Object, and

the Button, Submit, and Reset

Input Objects

For HTML element properties, methods, and event

han-dlers, see Chapter 15

value

Syntax

Accessing button object properties or methods:

(All) [window.]document.formName.buttonName.property |

method([parameters])

24C H A P T E R

In This Chapter

Triggering action from a user’s click of

a button Assigning hidden values to radio and checkbox buttons Distinguishing between radio button families and their individual buttons

Trang 3

550 Part III ✦ Document Objects Reference

(All) [window.]document.formName.elements[index].property |

method([parameters])

(All) [window.]document.forms[index].buttonName.property |

method([parameters])

(All) [window.]document.forms[“formName”].buttonName.property |

method([parameters])

(All) [window.]document.forms[“formName”].elements[index].property |

method([parameters])

(IE4+) [window.]document.all.elemID.property | method([parameters]) (IE5+/NN6) [window.]document.getElementById(“elemID”).property |

method([parameters])

About these objects

Button objects generate standard, pushbutton-style user interface elements on the page, depending on the operating system on which the particular browser runs

In the early days, the browsers called upon the operating systems to generate these standard interface elements In more recent versions, the browsers define their own look, albeit frequently still different for each operating system More recently, the appearance of a button may also be influenced by browser-specific customizations that browser makers put into their products Even so, any computer user will recog-nize a button when the browser produces it on the page

Starting with IE4 and NN6, you have two ways to put standard buttons into a page The first, and completely backward-compatible way, is to use INPUT elements nested inside a FORM container But a new HTML element, the BUTTON element, provides a slightly different way of specifying a button in a page, including the option of putting a button outside of a FORM (presumably for some client-side script execution, independent of form submission) From an HTML point of view, the difference between the two concerns itself with the way the label of the button

is specified With an INPUT element, the string assigned to the VALUEattribute becomes the label of the button; but a BUTTON element is a container (meaning with an end tag), whose content becomes the button’s label You can still assign a value to the VALUEattribute, which, if a form contains the button, gets submitted to the server, independent of the label text

Always give careful thought to the label that you assign to a button Because a button initiates some action, make sure that the verb in the label clearly defines what happens after you click it Also, take cues from experienced user interface designers who craft operating system and commercial software buttons: Be con-cise If you find your button labels going longer than two or three words, reconsider the design of your page so that the user can clearly understand the purpose of any button from a shorter label

Browsers automatically display a button sized to accommodate the label text But only browsers that support style sheets (IE4+ and NN6+) allow you to control more visual aspects of the button, such as size, label font, and coloration And, as for the position of the button on the page, buttons, as in all in-line elements, appear where they occur in the source code You can, of course, use element positioning of recent browsers (Chapter 31) to make a button appear wherever you want it But if your pages run on multiple operating systems and generations of browsers, be aware that the appearance (and size) of a button will not be identical on all screens Check out the results on as many platforms as possible

document.formObject.buttonObject

Trang 4

Buttons in the Windows environment follow their normal behavior in that they

indicate the focus with highlighted button-label text (usually with a dotted

rectan-gle) Some newer browsers running on other operating systems offer this kind of

highlighting and selection as a user option IE5 provides additional INPUT element

features that prevent buttons from receiving this kind of visible focus

The lone button object event handler that works on all browser versions is one

that responds to a user clicking the pointer atop the mouse: the onClickevent

handler Virtually all action surrounding a button object comes from this event

han-dler You rarely need to extract property values or invoke the click()method (the

method does not work correctly in Navigator 3) NN4 and IE4 add events for the

components of a click: mouseDownand mouseUp; and IE4+ and NN6+ provide a

plethora of user-initiated events for buttons

Two special variants of the buttonobject are the submit and reset button

objects With their heritages going back to early incarnations of HTML, these two

button types perform special operations on their own The submit-style button

automatically sends the data within the same form object to the URL listed in the

ACTIONattribute of the <FORM>definition The METHODattribute dictates the format

in which the button sends the data Therefore, you don’t have to script this action if

your HTML page is communicating with a CGI program on the server

If the form’s ACTIONattribute is set to a mailto:URL, you must provide the

page visitor with a Submit button to carry out the action Setting the form’s

ENC-TYPEattribute to text/plain is also helpful so that the form data arrives in a more

readable form than the normal encoded name-value pairs See “E-Mailing forms” in

Chapter 23 for details about submitting form content via e-mail

The partner of the Submit button is the Reset button This button, too, has

spe-cial powers A click of this button type restores all elements within the form to their

default values That goes for text objects, radio button groups, checkboxes, and

selection lists The most common application of the button is to clear entry fields of

the last data entered by the user

All that distinguishes these three types of buttons from each other in the

<INPUT>tag or <BUTTON>tag is the parameter of the TYPEattribute For buttons

not intended to send data to a server, use the “button” style (this is the default

value for the BUTTON element) Reserve “submit” and “reset” for their special

powers

If you want an image to behave like a button in all scriptable browsers, consider

either associating a link with an image (see the discussion on the link object in

Chapter 21) or creating a client-side image map (see the area object discussion in

Chapter 22) But for IE4+ and NN6+, you can use the INPUT element with a TYPE

attribute set to image(discussed later in this chapter)

Probably the biggest mistake scripters make with these buttons is using a

Submit button to do the work of a plain button Because these two buttons look

alike, and the submit type of input element has a longer tradition than the button,

confusing the two is easy But if all you want is to display a button that initiates

client-side script execution, use a plain button The Submit button attempts to

sub-mit the form If no ACTIONattribute is set, then the page reloads, and all previous

processing and field entries are erased The plain button does its job quietly

with-out reloading the page (unless the script intentionally does so)

document.formObject.buttonObject

Trang 5

552 Part III ✦ Document Objects Reference

Properties form

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

A property of every INPUT element object is a reference to the FORM element that contains the control This property can be very convenient in a script when you are dealing with one form control that is passed as a parameter to the function and you want to either access another control in the same form or invoke a method

of the form An event handler of any INPUT element can pass thisas the parame-ter, and the function can still get access to the form without having to hard-wire the script to a particular form name or document layout

Example on the CD-ROM

Related Items: FORM object.

name

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

A button’s name is fixed in the INPUT or BUTTON element’s NAMEattribute and cannot be adjusted via scripting except in newer browsers You may need to retrieve this property in a general-purpose function handler called by multiple but-tons in a document The function can test for a button name and perform the neces-sary statements for that button If you change the name of the object, even a soft reload or window resize restores its original name

Example on the CD-ROM

Related Items:nameproperty of all form elements

On the

CD-ROM

On the

CD-ROM

document.formObject.buttonObject.name

Trang 6

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

The precise value of the typeproperty echoes the setting of the TYPEattribute

of the <INPUT>or <BUTTON>tag that defines the object: button; submit; or reset

value

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

Both INPUT and BUTTON elements have the VALUEattribute, which is

repre-sented by the valueproperty in the object model But the purpose of the

attribute/property in the two elements differs For the INPUT element, the value

property represents the label displayed on the button For a BUTTON element,

however, the label text is created by the HTML text between the start and end tags

for the BUTTON element In both cases, when the element has a NAMEvalue

associ-ated with it, the name/value pair is submitted along with the form (assuming the

BUTTON element is inside a form)

If you do not assign a VALUEattribute to a reset or submit style button, the

browsers automatically assign the labels Resetand Submitwithout assigning a

value A value property can be any string, including multiple words

You can modify this text on the fly in a script, but some cautions apply Browsers

prior to IE4 and NN6 do not resize the width of the button to accommodate a new

name that is longer or shorter than the original Moreover, any soft reload or resize

of the window restores the original label IE4+ and NN6, however, resize the button

and reflow the page to meet the new space needs; the new label survives a window

resizing, but not a soft reload of the page Finally, IE4 for the Mac allows you to set

this property, but it doesn’t really stick

Example on the CD-ROM

Related Items:valueproperty of text object

On the

CD-ROM

document.formObject.buttonObject.value

Trang 7

554 Part III ✦ Document Objects Reference

Methods click()

Returns: Nothing.

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

A button’s click()method should simulate, via scripting, the human action of clicking that button Unfortunately, the method is highly unreliable in browsers prior to IE4 and NN4

Example on the CD-ROM

Related Items:onClickevent handler

Event handlers onClick

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

Virtually all button action takes place in response to the onClickevent handler

A click is defined as a press and release of the mouse button while the screen

pointer rests atop the button The event goes to the button only after the user releases the mouse button

For a Submit button, you should probably omit the onClickevent handler and allow the form’s onSubmitevent handler to take care of lastminute data entry vali-dation before sending the form By triggering valivali-dation with the onSubmitevent handler, your scripts can cancel the submission if something is not right (see the FORM object discussion in Chapter 23)

Example (with Listing 24-1) on the CD-ROM

Related Items:button.onMouseDown, button.onMouseUp, form.onSubmitevent handlers

On the

CD-ROM

On the

CD-ROM

document.formObject.buttonObject.onClick

Trang 8

onMouseUp

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

More recent browsers have event handlers for the components of a clickevent:

the onMouseDownand onMouseUpevent handlers These events fire in addition to

the onClickevent handler

The system-level buttons provided by the operating system perform their

change of appearance while a button is being pressed Therefore, trapping for the

components of a click action won’t help you in changing the button’s appearance

via scripting Remember that a user can roll the cursor off the button while the

but-ton is still down When the cursor leaves the region of the butbut-ton, the butbut-ton’s

appearance returns to its unpressed look, but any setting you make with the

onMouseDownevent handler won’t undo itself with an onMouseUpcounterpart, even

after the user releases the mouse button elsewhere On the other hand, if you can

precache a click-on and click-off sound, you can use these events to fire the

respec-tive sounds in response to the mouse button action

Related Items: button.onClickevent handler

Checkbox Input Object

For HTML element properties, methods, and event handlers, see Chapter 15

form†

name†

type

value

† See Button object.

Syntax

Accessing checkbox properties or methods:

(All) [window.]document.formName.boxName.property | method([parameters])

(All) [window.]document.formName.elements[index].property |

method([parameters])

(All) [window.]document.forms[index].boxName.property |

method([parameters])

(All) [window.]document.forms[“formName”].boxName.property |

method([parameters])

document.formObject.checkboxObject

Trang 9

556 Part III ✦ Document Objects Reference

(All) [window.]document.forms[“formName”].elements[index].property |

method([parameters])

(IE4+) [window.]document.all.elemID.property | method([parameters]) (IE5+/NN6) [window.]document.getElementById(“elemID”).property |

method([parameters])

About this object

Checkboxes have a very specific purpose in modern graphical user interfaces: to toggle between “on” and “off” settings As with a checkbox on a printed form, a mark in the box indicates that the label text is true or should be included for the individual who made that mark When the box is unchecked or empty, the text is false or should not be included If two or more checkboxes are physically grouped together, they should have no interaction: Each is an independent setting (see the discussion on the radio object for interrelated buttons)

I make these user interface points at the outset because, in order to present a user interface in your HTML pages consistent with the user’s expectations based on exposure to other programs, you must use checkbox objects only for on/off choices that the user makes Using a checkbox as an action button that, for example, navi-gates to another URL, is not good form Just as they do in a Windows or Mac dialog box, users make settings with checkboxes and radio buttons and initiate action by clicking a standard button or image map

That’s not to say that a checkbox object cannot perform some limited action in response to a user’s click, but such actions are typically related to the context of the checkbox button’s label text For example, in some Windows and Macintosh dia-log boxes, turning on a checkbox may activate a bunch of otherwise inactive set-tings elsewhere in the same dialog box IE4+ and NN6+ allow disabling (dimming) or hiding form elements, so a checkbox may control those visible attributes of related controls Or, in a two-frame window, a checkbox in one frame may control whether the viewer is an advanced user If so, the content in the other frame may be more detailed Toggling the checkbox changes the complexity level of a document show-ing in the other frame (usshow-ing different URLs for each level) The bottom line, then, is that you should use checkboxes for toggling between on/off settings Provide regu-lar buttons for users to initiate processing

In the <INPUT>tag for a checkbox, you can preset the checkbox to be checked when the page appears Add the constant CHECKEDattribute to the definition If you omit this attribute, the default, unchecked appearance rules As for the checkbox label text, its definition lies outside the <INPUT>tag If you look at the way check-boxes behave in HTML browsers, this location makes sense: The label is not an active part of the checkbox (as it typically is in Windows and Macintosh user inter-faces, where clicking the label is the same as clicking the box)

Naming a checkbox can be an important part of the object definition, depending

on how you plan to use the information in your script or document For forms whose content goes to a CGI program on the server, you must word the box name

as needed for use by the CGI program, so that the program can parse the form data and extract the setting of the checkbox For JavaScript client-side use, you can assign not only a name that describes the button, but also a value useful to your script for making if elsedecisions or for assembling strings that are eventually displayed in a window or frame

document.formObject.checkboxObject

Trang 10

checked

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

The simplest property of a checkbox reveals (or lets you set) whether or not a

checkbox is checked The value is truefor a checked box and falsefor an

unchecked box To check a box via a script, simply assign trueto the checkbox’s

checkedproperty:

document.forms[0].boxName.checked = true

Setting the checkedproperty from a script does not trigger a clickevent for

the checkbox object

You may need an instance in which one checkbox automatically checks another

checkbox elsewhere in the same or other form of the document To accomplish this

task, create an onClickevent handler for the one checkbox and build a statement

similar to the preceding one to set the other related checkbox to true Don’t get

too carried away with this feature, however: For a group of interrelated, mutually

exclusive choices, use a group of radio buttons instead

If your page design requires that a checkbox be checked after the page loads,

don’t bother trying to script this checking action Simply add the one-word

CHECKEDattribute to the <INPUT>tag Because the checkedproperty is a Boolean

value, you can use its results as an argument for an ifclause, as shown in the next

example

Example (with Listing 24-2) on the CD-ROM

Related Items:defaultChecked, valueproperties

defaultChecked

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

If you add the CHECKEDattribute to the <INPUT>definition for a checkbox, the

defaultCheckedproperty for that object is true; otherwise, the property is

false Having access to this property enables your scripts to examine checkboxes

to see if they have been adjusted (presumably by the user, if your script does not

set properties)

On the

CD-ROM

document.formObject.checkboxObject.defaultChecked

Ngày đăng: 06/07/2014, 06:20