Book HomeMac OS X for Unix GeeksSearch this book

Chapter 24. Client-Side JavaScript Reference

This part of the book is a reference section that documents the classes, methods, properties, and event handlers defined by web browsers that support client-side JavaScript. These classes, methods, and properties form the de facto standard called the DOM Level 0 API. Beginning scripters and programmers writing with backward compatibility in mind will use this reference section in conjunction with the core JavaScript reference of Part III. The introduction and sample reference page explain how to use and get the most out of this reference section. Take the time to read this material carefully, and you will find it easier to locate and use the information you need!

This reference section is arranged alphabetically. The reference pages for the methods and properties of classes are alphabetized by their full names, which include the names of the classes that define them. For example, if you want to read about the submit( ) method of the Form class, you would look under "Form.submit," not just "submit."

To save space in this enlarged fourth edition of the book, most properties in this reference section do not have reference pages of their own (all methods and event handlers do have their own reference pages, however). Instead, simple properties are completely documented in the reference page for the class that defines them. For example, you can read about the images[] property of the Document class in the "Document" reference page. Nontrivial properties that require substantial explanation do have reference pages of their own, and you'll find a cross-reference to these pages within the reference page of the class or interface that defines the properties. For example, when you look up the cookie property in the "Document" reference page or the status property in the "Window" reference page, you'll find a short description of the property and a reference to pages named "Document.cookie" and "Window.status."

Client-side JavaScript has a number of global properties and functions, such as window, history, and alert( ). In client-side JavaScript, a Window object serves as the global object, and the "global" properties and functions of client-side JavaScript are actually properties of the Window class. Therefore, in this client-side reference section, global properties and functions are documented in the "Window" reference page or under names such as "Window.alert( )."

Sometimes you may find that you don't know the name of the class or interface that defines the method or property you want to look up, or you may not be sure which of the three reference sections to look up a class or interface in. Part VI of this book is a special index designed to help with these situations. Look up the name of a class, method, or property, and it will tell you which reference section to look in and which class to look under in that section. For example, if you look up "Button," it will tell you that the Button class is documented in this client-side reference section. And if you look up the name "alert," it will tell you that alert( ) is a method of the client-side Window class.

Once you've found the reference page you're looking for, you shouldn't have much difficulty finding the information you need. Still, you'll be able to make better use of this reference section if you understand how the reference pages are written and organized. What follows is a sample reference page titled "Sample Entry" that demonstrates the structure of each reference page and tells you where to find various types of information within the pages. Take the time to read this page before diving into the rest of the reference material.

Sample Entryhow to read client-side reference pages

Availability

Availability

Inherits from/Overrides

Inherits from

Title and Short Description

Every reference entry begins with a title block like that above. The entries are alphabetized by title. The short description, shown next to the title, gives you a quick summary of the item documented in the entry; it can help you quickly decide if you're interested in reading the rest of the page.

Availability

The information in this section tells you when a class, method, or event handler was introduced. For some less portable items, this section specifies which versions of Netscape and Internet Explorer support it. If the item is well supported by web browsers and support was added by Netscape and IE within the same browser generation, this section specifies its availability in terms of a version of core JavaScript. You can use the tables in Chapter 1 to determine the particular releases of Netscape and Internet Explorer to which these versions correspond. Of course, since most properties do not have their own reference pages, they do not have availability information. If the availability of a property is different from the availability of the class that defines it, however, this fact is noted in the description of the property.

Inherits from

If a class inherits from a superclass, that information is shown in the "Inherits from" section. As described in Chapter 8, JavaScript classes can inherit properties and methods from other classes. For example, the Button class inherits from Input, which in turn inherits from HTMLElement. When you see this inheritance information, you may also want to look up the listed superclasses.

Synopsis

Every reference page has a "Synopsis" section that shows how you might use the class, method, or event handler in your code. For example, the synopsis for the Form class is:

document.form_name
document.forms[form_number] 

This synopsis shows two different ways of referring to a Form object. Text in this font must be typed exactly as shown. The italic font indicates text that is to be replaced with something else. form_name should be replaced with the name of a form, and form_number should be replaced with the index of the form in the forms[] array. Similarly, document should be replaced in these synopses with a reference to a Document object. By looking at the "Synopsis" section of the "Document" reference page, we discover that it also has two forms:

document
window.document 

That is, you can replace document with the literal document or with window.document. If you choose the latter, you'll need to look up the synopsis of the Window class to find out how to refer to a Window -- that is, what to replace window with.

Arguments

If a reference page documents a method, the "Synopsis" section is followed by an "Arguments" subsection that describes the arguments to the method. If the method has no arguments, this subsection is simply omitted.

arg1
The arguments are described in a list here. This is the description for argument arg1, for example.

arg2
And this is the description for argument arg2.

Returns

This section explains the method's return value. If the method does not return a value, this subsection is omitted.

Constructor

If the reference page documents a class that has a constructor method, this section shows you how to use the constructor method to create instances of the class. Since constructors are a type of method, the "Constructor" section looks a lot like the "Synopsis" section of a method's reference page and has an "Arguments" subsection as well.

Properties

If the reference page documents a class, the "Properties" section lists and documents the properties defined by that class. In this client-side reference section, only particularly complex properties have reference pages of their own.

prop1
This is documentation for property prop1, including its type, its purpose or meaning, and whether it is read-only or read/write.

prop2
This is the same for prop2.

Methods

The reference page for a class that defines methods includes a "Methods" section that lists the names of the methods and provides a short description of each. Full documentation for each method is found in a separate reference page.

Event Handlers

The reference page for a class that defines event handlers includes an "Event Handlers" section that lists the names of the handlers and provides a short description of each. Full documentation for each event handler is found in a separate reference page.

HTML Syntax

A number of client-side JavaScript classes have analogs in HTML. The reference pages for these classes include a section that shows the annotated HTML syntax used to create an HTML element that corresponds to a JavaScript object.

Description

Most reference pages contain a "Description" section, which is the basic description of the class, method, or event handler that is being documented. This is the heart of the reference page. If you are learning about a class, method, or handler for the first time, you may want to skip directly to this section and then go back and look at previous sections such as "Arguments," "Properties," and "Methods." If you are already familiar with an item, you probably won't need to read this section and instead will just want to quickly look up some specific bit of information (for example, from the "Arguments" or "Properties" sections).

In some entries, this section is no more than a short paragraph. In others, it may occupy a page or more. For some simple methods, the "Arguments" and "Returns" sections document the method sufficiently by themselves, so the "Description" section is omitted.

Example

A few pages include an example that shows typical usage. Most pages do not contain examples, however -- you'll find those in first half of this book.

Bugs

When an item doesn't work quite right, this section describes the bugs. Note, however, that this book does not attempt to catalog every bug in every version and implementation of client-side JavaScript.

See Also

Many reference pages conclude with cross-references to related reference pages that may be of interest. Most of these cross references are to other reference pages in this client-side reference section. Some are to individual property descriptions contained within a class reference page, however, and others are to related reference pages in the DOM reference section or to chapters in the first two parts of the book.

Anchorthe target of a hypertext link

Availability

JavaScript 1.2

Inherits from/Overrides

Inherits from HTMLElement

Synopsis

document.anchors[i] 
document.anchors.length

Properties

Anchor inherits properties from HTMLElement and defines or overrides the following:

name
Contains the name of an Anchor object. The value of this property is initially set by the name attribute of the <a> tag.

text [Netscape 4]
This property specifies the plain text, if any, between the <a> and </a> tags of an anchor. Note that this property works correctly only if there are no intervening HTML tags between the <a> and </a> tags. If there are other HTML tags, the text property may contain only a portion of the anchor text.

HTMLElement.innerText provides the IE 4 equivalent of this Netscape-specific property.

HTML Syntax

An Anchor object is created by any standard HTML <a> tag that contains a name attribute:

<a
  name="name"  // Links may refer to this anchor by this name
>
text
</a>

Description

An anchor is a named location within an HTML document. Anchors are created with an <a> tag that has a name attribute specified. The Document object has an anchors[] array property that contains Anchor objects that represent each of the anchors in the document. This anchors[] array has existed since JavaScript 1.0, but the Anchor object was not implemented until JavaScript 1.2. Therefore, the elements of anchors[] were null until JavaScript 1.2.

Note that the <a> tag used to create anchors is also used to create hypertext links. Although hypertext links are often called anchors in HTML parlance, they are represented in JavaScript with the Link object, not with the Anchor object. In the DOM reference section of this book, however, both anchors and links are documented under HTMLAnchorElement.

See Also

anchors[] property of the Document object, Link; HTMLAnchorElement in the DOM reference section

Appletan applet embedded in a web page Applet object

Availability

JavaScript 1.1

Synopsis

document.applets[i] 
document.appletName

Properties

The properties of an Applet object are the same as the public fields of the Java applet it represents.

Methods

The methods of an Applet object are the same as the public methods of the Java applet it represents.

Description

The Applet object represents a Java applet embedded in an HTML document. The properties of the Applet object represent the public fields of the applet, and the methods of the Applet object represent the public methods of the applet. LiveConnect technology in Netscape and ActiveX technology in Internet Explorer allow JavaScript programs to use the Applet object to read and write the fields and invoke the methods of the corresponding Java applet. See Chapter 22 for details.

Remember that Java is a strongly typed language. This means that each field of an applet has been declared to have a specific data type, and setting it to a value of some other type causes a runtime error. The same is true of applet methods: each argument has a specific type, and arguments cannot be omitted as they can be in JavaScript.

See Also

JavaObject; Chapter 22

Areasee Link

Buttona graphical push buttonButton object

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from Input, HTMLElement

Synopsis

form.button_name 
form.elements[i]

Properties

Button inherits properties from Input and HTMLElement and defines or overrides the following:

value
A string property that specifies the text that appears in the button. The value of this property is specified by the value attribute of the HTML <input> tag that creates the button. In browsers that cannot reflow document content, this property may be read-only.

Methods

Button inherits methods from Input and HTMLElement.

Event Handlers

Button inherits event handlers from Input and HTMLElement and defines or overrides the following:

onclick
Invoked when the button is clicked.

HTML Syntax

A Button element is created with a standard HTML <input> tag:

<form>
    ...
  <input
    type="button"          // Specifies that this is a button
    value="label"          // The text that is to appear within the button
                           // Specifies the value property
    [ name="name" ]        // A name you can use later to refer to the button
                           // Specifies the name property
    [ onclick="handler" ]  // JavaScript statements to be executed when the button
                           // is clicked
  >
    ...
</form>

Button objects can also be created with the HTML 4 <button> tag:

<button id="name"
        onclick="handler">
label
</button>

Description

The Button element represents a graphical push button in a form within an HTML document. The value property contains the text displayed by the button. The name property is the name the button may be referred to as. The onclick event handler is invoked when the user clicks on the button.

Usage

Use a Button element whenever you want to allow the user to trigger some action on your web page. You can sometimes use a Link object for the same purpose, but unless the desired action is to follow a hypertext link, a Button is a better choice than a Link, because it makes it more explicit to the user that there is something to be triggered.

Note that the Submit and Reset elements are types of Buttons that submit a form and reset a form's values. Often these default actions are sufficient for a form, and you do not need to create any other types of buttons.

Example

<form name="form1">
    <input type="button"
        name="press_me_button"
        value="Press Me"
        onclick="username = prompt('What is your name?',")"
    >
</form>

See Also

Form, HTMLElement, Input, Reset, Submit; HTMLInputElement in the DOM reference section

Button.onclickthe handler invoked when a Button is clicked

Availability

JavaScript 1.0

Synopsis

<input type="button" value="button-text" onclick="handler"> 
button.onclick

Description

The onclick property of a Button object refers to an event handler function that is invoked when the user clicks on the button. See HTMLElement.onclick for complete details. Note, however, that Button.onclick has been supported since JavaScript 1.0, unlike the generalized HTMLElement.onclick handler.

See Also

HTMLElement.onclick; Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

Checkboxa graphical checkbox

Availability

JavaScript 1.0; enhanced in JavaScript 1.1

Inherits from/Overrides

Inherits from Input, HTMLElement

Synopsis

A single Checkbox element with a unique name may be referenced in either of these ways:

form.checkbox_name
form.elements[i] 

When a form contains a group of checkboxes with the same name, they are placed in an array and may be referenced as follows:

form.checkbox_name[j]
form.checkbox_name.length 

Properties

Checkbox inherits properties from Input and HTMLElement and defines or overrides the following:

checked
A read/write boolean property. If the checkbox is checked, the checked property is true. If the checkbox is not checked, checked is false.

If you set checked to true, the checkbox appears checked. Similarly, if you set this property to false, the checkbox appears unchecked. Note that setting the checked property does not cause the Checkbox element's onclick event handler to be invoked.

defaultChecked
A read-only boolean that specifies the initial state of the checkbox. It is true if the checkbox is initially checked -- i.e., if the checked attribute appears in the checkbox's HTML <input> tag. If this attribute does not appear, the checkbox is initially unchecked and defaultChecked is false.

value
A read/write string property that specifies the text passed to the web server if the checkbox is checked when the form is submitted. The initial value of value is specified by the value attribute of the checkbox's HTML <input> tag. If no value attribute is specified, the default value string is "on".

Note that the value field does not specify whether the checkbox is selected; the checked property specifies the current state of the checkbox. When defining a group of related checkboxes that share the same name in a form that is submitted to the server, it is important that each be given a distinct value attribute.

Methods

Checkbox inherits the methods of Input and HTMLElement.

Event Handlers

Checkbox inherits event handlers from Input and HTMLElement and defines or overrides the following:

onclick
Invoked when the checkbox is clicked.

HTML Syntax

A Checkbox element is created with a standard HTML <input> tag. Multiple Checkbox elements are often created in groups by specifying multiple <input> tags that have the same name attribute.

<form>
    ...
  <input
    type="checkbox"        // Specifies that this is a checkbox
    [ name="name" ]        // A name you can use later to refer to this checkbox
                           // or to the group of checkboxes with this name
                           // Specifies the name property
    [ value="value" ]      // The value returned when this checkbox is selected
                           // Specifies the value property
    [ checked ]            // Specifies that the checkbox is initially checked
                           // Specifies the defaultChecked property
    [ onclick="handler" ]  // JavaScript statements to be executed
  >                        // when the checkbox is clicked
label                      // The HTML text that should appear next to the checkbox
    ...
</form>

Description

The Checkbox element represents a single graphical checkbox in an HTML form. Note that the text that appears next to the checkbox is not part of the Checkbox element itself and must be specified externally to the Checkbox's HTML <input> tag.

The onclick event handler allows you to specify JavaScript code to be executed when the checkbox is checked or unchecked. You can examine the checked property to determine the state of the checkbox and set this property to check or uncheck the checkbox. Note that setting checked changes the graphical appearance of the checkbox but does not invoke the onclick event handler.

It is good programming style to specify the name attribute for a checkbox; this is mandatory if the checkbox is part of a form that submits data to a CGI script running on a web server. Specifying a name attribute sets the name property and allows you to refer to the checkbox by name (instead of as a member of the form elements array) in your JavaScript code, which makes the code more modular and portable.

For example, if the name attribute of a checkbox in form f is "opts", f.opts refers to the Checkbox element. Checkbox elements are often used in related groups, however, and each member of the group is given the same name attribute (the shared name defines the members of the group). In this case, JavaScript places each Checkbox element in the group in an array, and the array is given the shared name. If, for example, each of a group of checkboxes in form f has its name attribute set to "opts", f.opts is an array of Checkbox elements, and f.opts.length is the number of elements in the array.

You can set the value attribute or the value property of a checkbox to specify the string that is passed to the server if the checkbox is checked when the form is submitted. For a single checkbox used alone, the default value of "on" is usually adequate. When multiple checkboxes with the same name are used, each should specify a distinct value so a list of values from selected checkboxes can be passed to the server.

Usage

Checkbox elements can present the user with one or more options. This element type is suitable for presenting non-mutually exclusive choices. Use the Radio element for mutually exclusive lists of options.

See Also

Form, HTMLElement, Input, Radio; HTMLInputElement in the DOM reference section

Checkbox.onclickthe handler invoked when a checkbox is selected

Availability

JavaScript 1.0

Synopsis

<input type="checkbox" onclick="handler"> 
checkbox.onclick

Description

The onclick property of a Checkbox object refers to an event handler function that is invoked when the user clicks on the checkbox. See HTMLElement.onclick for complete details. Note, however, that Checkbox.onclick has been supported since JavaScript 1.0, unlike the generalized HTMLElement.onclick handler.

See Also

HTMLElement.onclick; Chapter 19; EventListener, EventTarget, and MouseEvent in the DOM reference section

Documentrepresents an HTML document

Availability

JavaScript 1.0; enhanced in JavaScript 1.1, Netscape 4, and IE 4

Inherits from/Overrides

Inherits from HTMLElement

Synopsis

window.document 
document 

Properties

Document inherits properties from HTMLElement and defines the following properties. Netscape and Internet Explorer both define a number of incompatible Document properties that are used mostly for DHTML; they are listed separately after these properties.

alinkColor
alinkColor is a string property that specifies the color of activated links in document. Browsers may display this color between the times that the user presses and releases the mouse button over the link. The alink attribute of the <body> HTML tag specifies the initial value of this property. This property may be set, but only in the <head> of the document. See also the color properties of HTMLBodyElement in the DOM reference section.

anchors[]
An array of Anchor objects, one for each anchor that appears in document. An anchor is a named position within the document that can serve as the target of a hypertext link. The anchors[] array has anchors.length elements, numbered from zero to anchors.length-1. Do not confuse anchors with hypertext links, which are represented in JavaScript by the Link objects in the Document.links[] array.

Prior to JavaScript 1.2, the Anchor object was unimplemented, and the elements of anchors[] were all null.

applets[] [ JavaScript 1.1]
An array of Applet objects, one for each applet that appears in the document. You can use the Applet object to read and write all public variables in the applet, and you can invoke all of the applet's public methods. If an <applet> tag has a name attribute, the applet may also be referred to by using the name as a property of document or as an index into the applets array. Thus, if the first applet in a document has name="animator", you can refer to it in any of these ways:

document.applets[0]
document.animator
document.applets["animator"]
bgColor
A string property that specifies the background color of document. The initial value of this property comes from the bgcolor attribute of the <body> tag. The background color may be changed by assigning a value to bgColor. Unlike the other color properties, bgColor can be set at any time. See also the color properties of HTMLBodyElement in the DOM reference section.

cookie
A string that is the value of a cookie associated with this document. See the Document.cookie reference page.

domain
A string that specifies the document's Internet domain. Used for security purposes. JavaScript 1.1 and higher. See the Document.domain reference page.

embeds[] [ JavaScript 1.1]
An array of objects that represent data embedded in the document with the <embed> tag. The objects in the embeds[] array do not refer to the embedded data directly but refer instead to the object that displays that data. You can use the objects in the embeds[] array to interact with embedded data. The way you do this, however, is specific to the type of embedded data and the plugin or ActiveX control used to display it. Consult the developer's documentation for the plugin or ActiveX control to learn whether it can be scripted from JavaScript and, if so, what the supported APIs are.

Document.plugins[] is a synonym for Document.embeds[]. Do not confuse it with Navigator.plugins[].

fgColor
A string property that specifies the default color of text in document. The initial value of this property is from the text attribute of the <body> tag, and you can set the value of this property from a script within the <head> of the document. See also the color properties of HTMLBodyElement in the DOM reference section.

forms[]
An array of Form objects, one for each HTML form that appears in document. The forms[] array has forms.length elements, numbered from zero to forms.length-1.

images[] [ JavaScript 1.1]
An array of Image objects, one for each image that is embedded in the document with the HTML <img> tag. If the name attribute is specified in the <img> tag for an Image, a reference to that image is also stored in a property of the Document object. This property has the same name as the image. So if an image has a name="toggle" attribute, you can refer to the image with document.toggle.

lastModified
A read-only string that specifies the date of the most recent change to the document (as reported by the web server). See the Document.lastModified reference page.

linkColor
A string property that specifies the color of unvisited links in the document. The value of this property is set by the link attribute of the <body> tag, and it may also be set by a script in the <head> of the document. See also the color properties of HTMLBodyElement in the DOM reference section.

links[]
An array of Link objects, one for each hypertext link that appears in the document. The links[] array has links.length elements, numbered from zero to links.length-1.

location [Deprecated]
A Location object that contains the complete URL of the current document; a synonym for the Window.location property. In JavaScript 1.0, this property was instead a read-only string object that served the same purpose as the Document.URL property.

plugins[] [ JavaScript 1.1]
A synonym for the embeds[] array. Refers to an array of objects that represent the plugins or ActiveX controls used to display embedded data in a document. The embeds property is the preferred way to access this array, since it avoids confusion with the Navigator.plugins[] array.

referrer
A read-only string property that contains the URL of the document, if any, from which the current document was reached. For example, if the user follows a link in document A to document B, the Document.referrer property in document B contains the URL of document A. On the other hand, if the user types the URL of document B directly and does not follow any link to get there, the Document.referrer property for document B is an empty string.

title
A read-only string property that specifies the title of the current document. The title is any text that appears between the <title> and </title> tags in the <head> of the document.

URL
A read-only string that specifies the URL of the document. See the Document.URL reference page.

vlinkColor
A string property that specifies the color of visited links in document. The value of this property is set by the vlink attribute of the <body> tag, and you can also set it from a script within the <head> of the document. See also the color properties of HTMLBodyElement in the DOM reference section.

Netscape Properties

height [Netscape 4]
The height, in pixels, of the document.

layers[] [Netscape 4 only]
An array of Layer objects that represent the layers contained within a document. Each Layer object contains its own subdocument, accessible through the document property of the Layer object. This property is available only in Netscape 4; it has been discontinued in Netscape 6.

width [Netscape 4]
The width, in pixels, of the document.

Internet Explorer Properties

activeElement [IE 4]
A read-only property that refers to the input element within the document that is currently active (i.e., has the input focus).

all[] [IE 4]
An array of all elements within the document. See the Document.all[] reference page.

charset [IE 4]
The character set of the document.

children[] [IE 4]
An array that contains the HTML elements, in source order, that are direct children of the document. Note that this is different than the all[] array that contains all elements in the document, regardless of their position in the containment hierarchy.

defaultCharset [IE 4]
The default character set of the document.

expando [IE 4]
This property, if set to false, prevents client-side objects from being expanded. That is, it causes a runtime error if a program attempts to set the value of a nonexistent property of a client-side object. Setting expando to false can sometimes catch bugs caused by property misspellings, which can otherwise be difficult to detect. This property can be particularly helpful for programmers who are switching to JavaScript after becoming accustomed to case-insensitive languages. Although expando works only in IE 4, it can be set safely (if ineffectively) in Netscape.

parentWindow [IE 4]
The window that contains the document.

readyState
Specifies the loading status of a document. It has one of the following four string values:

uninitialized
The document has not started loading.

loading
The document is loading.

interactive
The document has loaded sufficiently for the user to interact with it.

complete
The document is completely loaded.

Methods

Document inherits methods from HTMLElement and defines the following methods. Netscape and IE both define a number of incompatible Document methods that are used mostly for DHTML; they are listed separately.

clear( )
Erases the contents of the document. This method is deprecated in JavaScript 1.1.

close( )
Closes a document stream opened with the open( ) method.

open( )
Opens a stream to which document contents may be written.

write( )
Inserts the specified string or strings into the document currently being parsed or into a document stream opened with open( ).

writeln( )
Identical to write( ), except that it appends a newline character to the output.

Netscape Methods

captureEvents( )
Requests events of specified types.

getSelection( )
Returns the currently selected document text.

releaseEvents
Stops capturing specified event types.

routeEvent( )
Routes a captured event to the next interested element. See Window.routeEvent( ).

Internet Explorer Methods

elementFromPoint( )
Returns the element located at a given (X-coordinate, Y-coordinate) point.

Event Handlers

The <body> tag has onload and onunload attributes. Technically, however, the onload and onunload event handlers belong to the Window object rather than the Document object. See Window.onload and Window.onunload.

HTML Syntax

The Document object obtains values for a number of its properties from attributes of the HTML <body> tag. Also, the HTML contents of a document appear between the <body> and </body> tags:

<body
  [ background="imageURL" ]  // A background image for the document
  [ bgcolor="color" ]        // A background color for the document
  [ text="color" ]           // The foreground color for the document's text
  [ link="color" ]           // The color for unvisited links
  [ alink="color" ]          // The color for activated links
  [ vlink="color" ]          // The color for visited links
  [ onload="handler" ]       // JavaScript to run when the document is loaded
  [ onunload="handler" ]     // JavaScript to run when the document is unloaded
>
// HTML document contents go here
</body>

Description

The Document object represents the HTML document displayed in a browser window or frame (or layer, in Netscape 4). The properties of this object provide details about many aspects of the document, from the colors of the text, background, and anchors, to the date on which the document was last modified. The Document object also contains a number of arrays that describe the contents of the document. The links[] array contains one Link object for each hypertext link in the document. Similarly, the applets[] array contains one object for each Java applet embedded in the document, and the forms[] array contains one Form object for each HTML form that appears in the document.

The write( ) method of the Document object is especially notable. When invoked in scripts that are run while the document is loading, you can call document.write( ) to insert dynamically generated HTML text into the document.

See Chapter 14 for an overview of the Document object and of many of the JavaScript objects to which it refers. See Chapter 17 for an overview of the DOM standard.

See Also

Form, the document property of the Window object; Chapter 14; Document, HTMLDocument, and HTMLBodyElement in the DOM reference section

Document.all[]all HTML elements in a document Internet Explorer 4

Synopsis

document.all[i] 
document.all[name]
document.all.tags(tagname)

Description

all[] is a versatile array that contains all the HTML elements in a document. all[] contains the elements in source order, and you can extract them directly from the array if you know their exact numeric position within the array. It is more common, however, to use the all[] array to retreive elements by the value of their name or id HTML attributes. If more than one element has the specified name, using that name as an index into the all[] returns an array of elements that share the name.

all.tags( ) is passed a tag name and returns an array of HTML elements of the specified type.

See Also

HTMLElement

Document.captureEvents( )see Window.captureEvents( )

Document.clear( )clear a document

Availability

JavaScript 1.0; deprecated

Synopsis

document.clear( ) 

Description

The clear( ) method of the Document object is deprecated and should not be used. To clear a document, you should simply open a new one with Document.open( ).

See Also

Document.close( ), Document.open( ), Document.write( )

Document.close( )close an output stream

Availability

JavaScript 1.0

Synopsis

document.close( ) 

Description

This method displays any output to document that has been written but not yet displayed and closes the output stream to document. When generating complete HTML pages with Document.write( ), you should invoke Document.close( ) when you reach the end of the page.

After document.close( ) has been called, if any further output is written to document (e.g., with document.write( )), the document is implicitly cleared and reopened, erasing all the output that was written prior to calling the close( ) method.

See Also

Document.open( ), Document.write( )

Document.cookiethe cookie(s) of the document

Availability

JavaScript 1.0

Synopsis

document.cookie 

Description

cookie is a string property that allows you to read, create, modify, and delete the cookie or cookies that apply to the current document. A cookie is a small amount of named data stored by the web browser. It gives web browsers a "memory" so they can use data input on one page in another page or recall user preferences across web browsing sessions. Cookie data is automatically transmitted between web browser and web server when appropriate so CGI scripts on the server end can read and write cookie values. Client-side JavaScript code can also read and write cookies with this property.

The Document.cookie property does not behave like a normal read/write property. You may both read and write the value of Document.cookie, but the value you read from this property is, in general, not the same as the value you write. For complete details on the use of this particularly complex property, see Chapter 16.

Usage

Cookies are intended for infrequent storage of small amounts of data. They are not intended as a general-purpose communication or programming mechanism, so use them in moderation. Note that web browsers are not required to retain the value of more than 20 cookies per web server (for the entire server, not just for your site on the server), nor to retain a cookie name/value pair of more than 4 KB in length.

See Also

Chapter 16

Document.domainthe security domain of a document

Availability

JavaScript 1.1

Synopsis

document.domain 

Description

For security reasons, an unsigned script running in one window is not allowed to read properties of another window unless that window comes from the same web server as the host. This causes problems for large web sites that use multiple servers. For example, a script on the host www.oreilly.com might want to share properties with a script from the host search.oreilly.com.

The domain property helps to address this problem. Initially, this string property contains the hostname of the web server from which the document was loaded. You can set this property, but only in a very restricted way: it can be set only to a domain suffix of itself. For example, a script loaded from search.oreilly.com could set its own domain property to "oreilly.com". If a script from www.oreilly.com is running in another window, and it also sets its domain property to "oreilly.com", these two scripts can share properties, even though they did not originate on the same server.

Note, however, that a script from search.oreilly.com cannot set its domain property to "search.oreilly". And, more importantly, a script from snoop.spam.com cannot set its domain to "oreilly.com", which might allow it to determine, for example, which search keywords you use.

See Also

Chapter 21

Document.elementFromPoint( )determine which HTML element is at a given point

Availability

Internet Explorer 4

Synopsis

document.elementFromPoint(x, y)

Arguments

x
The X-coordinate.

y
The Y-coordinate.

Returns

The HTML element that appears at point (x, y) in document.

Document.getSelection( )return the selected text Netscape 4

Synopsis

document.getSelection( )

Returns

The text, if any, that is currently selected within the document. This returned text has HTML formatting tags removed.

Document.handleEvent( )see Window.handleEvent( )

Document.lastModifiedthe modification date of a document

Availability

JavaScript 1.0

Synopsis

document.lastModified 

Description

lastModified is a read-only string property that contains the date and time at which document was most recently modified. This data is derived from HTTP header data sent by the web server. The web server generally obtains the last-modified date by examining the modification date of the file itself.

Web servers are not required to provide last-modified dates for the documents they serve. When a web server does not provide a last-modified date, JavaScript assumes 0, which translates to a date of midnight, January 1, 1970, GMT. The following example shows how you can test for this case.

Example

It is a good idea to let readers know how recent the information you provide on the Web is. You can include an automatic timestamp in your documents by placing the following script at the end of each HTML file. Doing this means you do not need to update the modification time by hand each time you make a change to the file. Note that this script tests that the supplied date is valid before displaying it:

<script>
if (Date.parse(document.lastModified) != 0)
    document.write('<p><hr><small><i>Last modified: '
                   + document.lastModified
                   + '</i></small>');
</script> 

See Also

The Document location, referrer, and title properties

Document.links[]the Link objects in a document

Availability

JavaScript 1.0

Synopsis

document.links 
document.links.length

Description

The links property is an array of Link objects -- one object for each hypertext link that appears in document. The links[] array has links.length elements, numbered from zero to links.length-1.

See Also

Link

Document.open( )begin a new document

Availability

JavaScript 1.0

Synopsis

document.open( ) 
document.open(mimetype)

Arguments

mimetype
An optional string argument that specifies the type of data to be written to and displayed in document. The value of this argument should be one of the standard MIME types that the browser understands ("text/html", "text/plain", "image/gif", "image/jpeg", and "image/x-bitmap" for Netscape) or some other MIME type that can be handled by an installed plugin. If this argument is omitted, it is taken to be "text/html". This argument is ignored by IE 3, which always assumes a document of type "text/html". This argument is also not supported in the standard W3C DOM version of this method. See the HTMLDocument.open( ) entry in the DOM reference section.

Description

The document.open( ) method opens a stream to document so subsequent document.write( ) calls can append data to the document. The optional mimetype argument specifies the type of data to be written and tells the browser how to interpret that data.

If any existing document is displayed when the open( ) method is called, it is automatically cleared by the call to open( ) or by the first call to write( ) or writeln( ). After opening a document with open( ) and writing data to it with write( ), you should complete the document by calling close( ).

Usage

You usually call Document.open( ) with no argument to open an HTML document. Occasionally, a "text/plain" document is useful, for example, for a pop-up window of debugging messages.

See Also

Document.close( ), Document.write( ); HTMLDocument.open( ) in the DOM reference section

Document.releaseEvents( )see Window.releaseEvents( )

Document.routeEvent( )see Window.routeEvent( )

Document.URLthe URL of the current document

Availability

JavaScript 1.1

Synopsis

document.URL 

Description

URL is a read-only string property that contains the complete URL of the current document.

document.URL is usually equal to window.location.href for the window that contains document. These two are not always equal, however, because the Document.URL property may be modified through URL redirection -- Window.location contains the requested URL, and Document.URL specifies the actual URL where it was found.

Usage

Some web authors like to include the URL of a document somewhere within the document so, for example, if the document is cut-and-pasted to a file or printed out, there is still a reference to its location online. The following script, when appended to a document, automatically adds the document's URL:

<script>
document.write('<p><hr><small><i>URL: ' + document.URL
    + '</i></small>');
</script>

See Also

The lastModified, location, referrer, and title properties of the Document object; the location property of the Window object

Document.write( )append data to a document

Availability

JavaScript 1.0

Synopsis

document.write(value, ...)

Arguments

value
An arbitrary JavaScript value to be appended to document. If the value is not a string, it is converted to one before being appended.

...
Any number (zero or higher) of additional values to be appended (in order) to document.

Description

document.write( ) appends each of its arguments, in order, to document. Any arguments that are not strings are converted to strings before they are written to the end of the document.

Document.write( ) is usually used in one of two ways. First, it can be invoked on the current document within a <script> tag or within a function that is executed while the document is being parsed. In this case, the write( ) method writes its HTML output as if that output appeared literally in the file at the location of the code that invoked the method.

Second, you can use Document.write( ) to dynamically generate the contents of a document for a window other than the current window. In this case, the target document is never in the process of being parsed, and so the output cannot appear "in place" as it does in the case just described. In order for write( ) to output text into a document, that document must be open. You can open a document by explicitly calling the Document.open( ) method. In most cases this is unnecessary, however, because when write( ) is invoked on a document that is closed, it implicitly opens the document. When a document is opened, any contents that previously appeared in that document are discarded and replaced with a blank document.

Once a document is open, Document.write( ) can append any amount of output to the end of the document. When a new document has been completely generated by this technique, the document should be closed by calling Document.close( ). Note that although the call to open( ) is usually optional, the call to close( ) is never optional.

The results of calling Document.write( ) may not be immediately visible in the targeted web browser window or frame. This is because a web browser may buffer up data to output in larger chunks. Calling Document.close( ) is the only way to explicitly force all buffered output to be "flushed" and displayed in the browser window.

See Also

Document.close( ), Document.open( ), Document.writeln( ); Chapter 14

Document.writeln( )append data and a newline to a document

Availability

JavaScript 1.0

Synopsis

document.writeln(value, ...)

Arguments

value
An arbitrary JavaScript value to be appended to document. If the value is not a string, it is converted to one before being appended.

...
Any number (zero or higher) of additional values to be appended (in order) to document.

Description

Document.writeln( ) behaves just like Document.write( ) except that after appending all of its arguments to document, it also appends a newline character. See the Document.write( ) reference page for more information on this method.

Newline characters are not usually displayed in HTML documents, so Document.writeln( ) is generally useful only when writing text to appear in a <pre> environment, or when writing to a document opened with a MIME type of "text/plain".

See Also

Document.close( ), Document.open( ), Document.write( )

Elementsee Input

Eventdetails about an event

Availability

JavaScript 1.2; incompatible versions supported by Netscape 4 and IE 4

Synopsis

function handler(event) { ... } // Event handler argument in Netscape 4 
window.event   // Window property in IE 4

Constants

In Netscape 4, the Event object defines bitmask constants for each of the supported event types. These static properties are used to form the bitmasks that are passed to captureEvents( ) and releaseEvents( ). The available constants are:

Event.ABORT
Event.BLUR
Event.CHANGE
Event.CLICK
Event.DBLCLICK
Event.DRAGDROP
Event.ERROR
Event.FOCUS
Event.KEYDOWN
Event.KEYPRESS
Event.KEYUP
Event.LOAD
Event.MOUSEDOWN
Event.MOUSEMOVE
Event.MOUSEOUT
Event.MOUSEOVER
Event.MOUSEUP
Event.MOVE
Event.RESET
Event.RESIZE
Event.SELECT
Event.SUBMIT
Event.UNLOAD

Netscape 4 Properties

height
Set only in events of type "resize". Specifies the new height of the window or frame that was resized.

layerX, layerY
Specify the X- and Y-coordinates, relative to the enclosing layer, at which an event occurred.

modifiers
Specifies which keyboard modifier keys were held down when the event occurred. This numeric value is a bitmask consisting of any of the constants Event.ALT_MASK, Event.CONTROL_MASK, Event.META_MASK, or Event.SHIFT_MASK. Due to a bug, this property is not defined in Netscape 6 or 6.1.

pageX, pageY
Specify the X- and Y-coordinates, relative to the web browser page, at which the event occurred. Note that these coordinates are relative to the top-level page, not to any enclosing layers.

screenX, screenY
Specify the X- and Y-coordinates, relative to the screen, at which the event occurred. Note that, unlike most Event properties, these properties are supported by and have the same meaning in both Netscape 4 and Internet Explorer 4.

target
Specifies the Window, Document, Layer, or HTMLElement object on which the event occurred.

type
A string property that specifies the type of the event. Its value is the name of the event handler minus the "on" prefix. So when the onclick( ) event handler is invoked, the type property of the Event object is "click".

which
For keyboard and mouse events, which specifies which key or mouse button was pressed or released. For keyboard events, this property contains the character encoding of the key that was pressed. For mouse events, it contains 1, 2, or 3, indicating the left, middle, or right buttons.

width
Set only in events of type "resize". Specifies the new width of the window or frame that was resized.

x, y
Specify the X- and Y-coordinates at which the event occurred. In Netscape 4, these properties are synonyms for layerX and layerY and specify the position relative to the containing layer (if any). Their meaning is different in Internet Explorer (see below).

Internet Explorer 4 Properties

altKey
A boolean value that specifies whether the Alt key was held down when the event occurred.

button
For mouse events, button specifies which mouse button or buttons were pressed. This read-only integer is a bitmask: the 1 bit is set if the left button was pressed; the 2 bit is set if the right button was pressed; and the 4 bit is set if the middle button (of a three-button mouse) was pressed.

cancelBubble
If an event handler wants to stop an event from being propagated up to containing objects, it must set this property to true.

clientX, clientY
Specify the X- and Y-coordinates, relative to the web browser page, at which the event occurred.

ctrlKey
A boolean value that specifies whether the Ctrl key was held down when the event occurred.

fromElement
For mouseover and mouseout events, fromElement refers to the object from which the mouse pointer is moving.

keyCode
For keyboard events, keyCode specifies the Unicode character code generated by the key that was struck.

offsetX, offsetY
Specify the X- and Y-coordinates at which the event occurred within the coordinate system of the event's source element (see srcElement).

reason
For the datasetcomplete event, reason contains a code that specifies the status of the data transfer. A value of 0 indicates a successful transfer. A value of 1 indicates that the transfer was aborted. A value of 2 indicates that an error occurred during data transfer.

returnValue
If this property is set, its value takes precedence over the value actually returned by an event handler. Set this property to false to cancel the default action of the source element on which the event occurred.

screenX, screenY
Specify the X- and Y-coordinates, relative to the screen, at which the event occurred. Note that, unlike most Event properties, these two properties are supported by and have the same meaning in both Netscape 4 and Internet Explorer 4.

shiftKey
A boolean value that specifies whether the Shift key was held down when the event occurred.

srcElement
A reference to the Window, Document, or HTMLElement object that generated the event.

srcFilter
For filterchange events, srcFilter specifies the filter that changed.

toElement
For mouseover and mouseout events, toElement refers to the object into which the mouse pointer is moving.

type
A string property that specifies the type of the event. Its value is the name of the event handler minus the "on" prefix. So when the onclick( ) event handler is invoked, the type property of the Event object is "click".

x, y
Specify the X- and Y-coordinates at which the event occurred. In Internet Explorer 4, this property specifies the X position relative to the innermost containing element that is dynamically positioned using CSS. The interpretation of these properties is different in Netscape 4 (see the previous section).

Description

The Event object provides details about an event that has occurred. Unfortunately, these details are not standardized, and Netscape 4 and IE 4 define Event objects that are almost entirely incompatible. Besides having different properties, Netscape 4 and IE 4 provide access to Event objects in different ways. In Netscape, an Event object is passed as an argument to every event handler. For event handlers defined by HTML attributes, the name of the event argument is event. In IE, the Event object of the most recent event is instead stored in the event property of the Window object.

In addition to the incompatibility between the Netscape 4 Event object and the IE Event object, the W3C DOM defines its own Event object that is incompatible with both. See the Event, UIEvent, and MouseEvent entries in the DOM reference section.

See Also

Chapter 19; Event, UIEvent, and MouseEvent in the DOM reference section

FileUploada file upload field for form input

Availability

JavaScript 1.0 Inherits from Input, HTMLElement

Synopsis

form.name
form.elements[i]

Properties

FileUpload inherits properties from Input and HTMLElement and defines or overrides the following:

value [ JavaScript 1.1]
A read-only string that specifies the filename entered by the user into the FileUpload object. The user may enter a filename either by typing it directly or by using the directory browser associated with the FileUpload object.

To prevent malicious programs from uploading arbitrary files from the client, this property may not be set by JavaScript code. Similarly, the value attribute of the <input> tag does not specify the initial value for this property.

Methods

FileUpload inherits methods from Input and HTMLElement.

Event Handlers

FileUpload inherits event handlers from Input and HTMLElement and defines or overrides the following:

onchange
Invoked when the user changes the value in the FileUpload element and moves the keyboard focus elsewhere. This event handler is not invoked for every keystroke in the FileUpload element, but only when the user completes an edit.

HTML Syntax

A FileUpload element is created with a standard HTML <input> tag:

<form enctype="multipart/form-data"
      method="post">         // Required attributes
    ...
  <input
    type="file"              // Specifies that this is a FileUpload element
    [ name="name" ]          // A name you can use later to refer to this element
                             // Specifies the name property
    [ size="integer" ]       // How many characters wide the element is
    [ maxlength="integer" ]  // Maximum allowed number of input characters
    [ onblur="handler" ]     // The onblur( ) event handler
    [ onchange="handler" ]   // The onchange( ) event handler
    [ onfocus="handler" ]    // The onfocus( ) event handler
  >
    ...

Description

The FileUpload element represents a file upload input element in a form. In many respects, this input element is much like the Text element. On the screen, it appears like a text input field with the addition of a Browse button that opens a directory browser. Entering a filename into a FileUpload element (either directly or through the browser) causes Netscape to submit the contents of that file along with the form. For this to work, the form must use "multipart/form-data" encoding and the POST method.

The FileUpload element does not have a defaultValue property and does not recognize the value HTML attribute to specify an initial value for the input field. Similarly, the value property of the FileUpload element is read-only. Only the user may enter a filename; JavaScript may not enter text into the FileUpload field in any way. This is to prevent malicious JavaScript programs from uploading arbitrary files (such as password files) from the user's machine.

See Also

Form, HTMLElement, Input, Text; HTMLInputElement in the DOM reference section

FileUpload.onchangethe handler invoked when input value changes

Available

JavaScript 1.0

Synopsis

<input type="file" onchange="handler"...> 
fileupload.onchange

Description

The onchange property of a FileUpload element specifies an event handler function that is invoked when the user changes the value in the input field (either by typing directly or using the Browse button) and then moves input focus elsewhere. This handler is intended to process a complete change to the input value and therefore is not invoked on a keystroke-by-keystroke basis.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onchange attribute of the HTML tag that defined the object. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than in the scope of the containing window.

In the Netscape 4 event model, the onchange handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

See Also

Input.onchange; Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Forman HTML input form

Availability

JavaScript 1.0 Inherits from HTMLElement

Synopsis

document.form_name 
document.forms[form_number]

Properties

Form inherits properties from HTMLElement and defines or overrides the following:

action
A read/write string (read-only in IE 3) that specifies the URL to which the form data is sent when the form is submitted. The initial value of this property is specified by the action attribute of the <form> HTML tag. Usually, this URL specifies the address as a CGI script, although it can also be a mailto: or news: address.

elements[]
An array of input elements that appear in the form. Each element is a Button, Checkbox, Hidden, Password, Radio, Reset, Select, Submit, Text, or Textarea object. See the Form.elements[] reference page.

encoding
A read/write string (read-only in IE 3) that specifies how form data is encoded for transmission when the form is submitted. The initial value of this property is specified by the enctype attribute of the <form> tag. The default value is "application/x-www-form-urlencoded", which is sufficient for almost all purposes. Other values may sometimes be necessary. For example, a value of "text/plain" is convenient when the form is submitted by email to a mailto: URL. See CGI Programming on the World Wide Web, by Shishir Gundavaram (O'Reilly), for further information.

length
The number of elements in the form. Equivalent to elements.length.

method
A read/write string (read-only in IE 3) that specifies the method by which form data is submitted. The initial value of this property is specified by the method attribute of the <form> tag. The two legal values are get and post.

The get method is the default. It is usually used for form submissions such as database queries that do not have side effects. With this method, the encoded form data is appended to the URL specified by the Form.action property. The post method is appropriate for form submissions, such as additions to databases, that have side effects. With this method, encoded form data is sent in the body of the HTTP request.

name
Specifies the name of the form. The initial value of this read/write string property is the value of the name attribute of the <form> tag.

target
A read/write string that specifies the name of the frame or window in which the results of submitting a form should be displayed. Initially specified by the target attribute. The special names "_top", "_parent", "_self", and "_blank" are also supported for the target property and the target attribute. See the Form.target reference page.

Methods

Form inherits methods from HTMLElement and defines the following:

reset( )
Resets each of the input elements of the form to their default values.

submit( )
Submits the form.

Event Handlers

Form inherits event handlers from HTMLElement and defines the following:

onreset
Invoked just before the elements of the form are reset. Specified in HTML by the onreset attribute.

onsubmit
Invoked just before the form is submitted. Specified in HTML by the onsubmit attribute. This event handler allows form entries to be validated before being submitted.

HTML Syntax

A Form object is created with a standard HTML <form> tag. The form contains any input elements created with the <input>, <select>, and <textarea> tags between <form> and </form>:

<form
    [ name="form_name" ]       // Used to name the form in JavaScript
    [ target="window_name" ]   // The name of the window for responses
    [ action="url" ]           // The URL to which the form is submitted
    [ method=("get"|"post") ]  // The method of form submission
    [ enctype="encoding" ]     // How the form data is encoded
    [ onreset="handler" ]      // A handler invoked when form is reset
    [ onsubmit="handler" ]     // A handler invoked when form is submitted
>
// Form text and input elements go here
</form> 

Description

The Form object represents an HTML <form> in a document. Each form in a document is represented as an element of the Document.forms[] array. Named forms are also represented by the form_name property of their document, where form_name is the name specified in the name attribute of the <form> tag.

The elements of a form (buttons, input fields, checkboxes, and so on) are collected in the Form.elements[] array. Named elements, like named forms, can also be referenced directly by name -- the element name is used as a property name of the Form object. Thus, to refer to a Text object element named phone within a form named questionnaire, you might use the JavaScript expression:

document.questionnaire.phone

See Also

Button, Checkbox, FileUpload, Hidden, Input, Password, Radio, Reset, Select, Submit, Text, Textarea; Chapter 15; HTMLFormElement in the DOM reference section

Form.elements[]the input elements of the form

Availability

JavaScript 1.0

Synopsis

form.elements[i] 
form.elements.length

Description

form.elements[] is an array of the form input objects in form. The array has elements.length items in it. These items may be of any of the form input element types: Button, Checkbox, Hidden, Password, Radio, Reset, Select, Submit, Text, and Textarea. These form input objects appear in the array in the same order that they appear in the HTML source code for the form.

Usage

If an item in the form.elements[] array has been given a name with the name="name" attribute of its HTML <input> tag, that item's name becomes a property of form, and this property refers to the item. Thus, it is possible to refer to input objects by name instead of by number:

form.name 

Referring to elements by name is usually easier, so it is a good idea to specify the name attribute for all form elements.

See Also

Button, Checkbox, Form, Hidden, Input, Password, Radio, Reset, Select, Submit, Text, Textarea

Form.onresetthe handler invoked when a form is reset

Availability

JavaScript 1.1

Synopsis

<form ... onreset="handler" ... >
form.onreset

Description

The onreset property of a Form object specifies an event handler function that is invoked when the user clicks on a Reset button in the form or when Form.reset( ) is called.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onreset attribute of the HTML <form> tag. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than the scope of the containing window.

In the Netscape 4 event model, the onreset handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

If the onreset handler returns false, the elements of the form are not reset.

Example

You could use the following event handler to ask the user to confirm that they really want to reset the form:

<form ...
    onreset="return confirm('Really erase all entered data?')"
> 

See Also

Form.onsubmit, Form.reset( ); Chapter 19; Section , EventListener, and EventTarget in the DOM reference section

Form.onsubmitinvoked when a form is submitted

Availability

JavaScript 1.0

Synopsis

<form ... onsubmit="handler" ... >
form.onsubmit

Description

The onsubmit property of a Form object specifies an event handler function that is invoked when the user submits a form by clicking on a Submit button in the form. Note that this event handler is not invoked when the Form.submit( ) method is called.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onsubmit attribute of the HTML <form> tag. When an event handler function is defined by an HTML attribute, it is executed in the scope of element rather than the scope of the containing window.

In the Netscape 4 event model, the onsubmit handler function is passed an Event object as an argument. In the IE event model, no argument is passed, but the applicable Event object is available as the event property of the Window object that contains the element.

If the onsubmit handler returns false, the elements of the form are not submitted. If the handler returns any other value or returns nothing, the form is submitted normally. Because the onsubmit handler can cancel form submission, it is ideal for performing form data validation.

See Also

Form.onreset, Form.submit( ); Chapter 19; Event, EventListener, and EventTarget in the DOM reference section

Form.reset( )reset the elements of a form

Availability

JavaScript 1.1

Synopsis

form.reset( ) 

Description

The reset( ) method resets the specified form, restoring each element of the form to its default value, exactly as if a Reset button had been pressed by the user. The form's onreset( ) event handler is first invoked and may prevent the reset from occurring by returning the value false.

Form.submit( )submit a formJavaScript 1.0

Availability

Synopsis

form.submit( ) 

Description

The submit( ) method submits the specified form, almost as if a Submit button had been pressed by the user. The form is submitted as specified by the action, method, and encoding properties of form (or the action, method, and enctype attributes of the <form> tag), and the results are displayed in the window or frame specified by the target property or the target attribute.

The one important difference between the submit( ) method and form submission by the user is that the onsubmit( ) event handler is not invoked when submit( ) is called. If you use onsubmit( ) to perform input validation, for example, you'll have to do that validation explicitly before calling submit( ).

Usage

It is more common to use a Submit button that allows the user to submit the form than to call the submit( ) method yourself.

Form.targetthe window for form results

Availability

JavaScript 1.0;

Inherits from/Overrides

read-only in Internet Explorer 3

Synopsis