Scripting Form Elements

The previous section listed the form elements provided by HTML and explained how to embed these elements in your HTML documents. This section takes the next step and shows you how you can work with those elements in your JavaScript programs.

Naming Forms and Form Elements

Every form element has a name attribute that must be set in its HTML tag if the form is to be submitted to a server-side program. While form submission is not generally of interest to JavaScript programs, there is another useful reason to specify this name attribute, as you’ll see shortly.

The <form> tag itself also has a name attribute that you can set. This attribute has nothing to do with form submission. It exists for the convenience of JavaScript programmers. If the name attribute is defined in a <form> tag, when the Form object is created for that form, it is stored as an element in the forms[] array of the Document object, as usual, and it is also stored in its own personal property of the Document object. The name of this newly defined property is the value of the name attribute. In Example 15-1, for instance, we defined a form with a tag like this:

<form name="everything">

This allowed us to refer to the Form object as:

document.everything

Often, you’ll find this more convenient than the array notation:

document.forms[0]

Furthermore, using a form name makes your code position-independent: it works even if the document is rearranged so that forms appear in a different order.

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.