Home > Articles > Open Source > Ajax & JavaScript

This chapter is from the book

Scripting Form Elements

The most important property of the form object is the elements array, which contains an object for each of the form elements. You can refer to an element by its own name or by its index in the array. For example, the following two expressions both refer to the first element in the order form, the name1 text field:



Both forms and elements can be referred to by their own names or as indices in the forms and elements arrays. For clarity, the examples in this hour use individual form and element names rather than array references. You'll also find it easier to use names in your own scripts.

If you do refer to forms and elements as arrays, you can use the length property to determine the number of objects in the array: document.forms.length is the number of forms in a document, and document.form1.elements.length is the number of elements in the form1 form.

Text Fields

Probably the most commonly used form elements are text fields. You can use them to prompt for a name, address, or any information. With JavaScript, you can display text in the field automatically. The following is an example of a simple text field:

<input TYPE="TEXT" NAME="text1" VALUE="hello" size="30">

This defines a text field called text1. The field is given a default value of "hello" and allows up to 30 characters to be entered. JavaScript treats this field as a text object with the name text1.

Text fields are the simplest to work with in JavaScript. Each text object has the following properties:

  • name is the name given to the field. This is also used as the object name.

  • defaultValue is the default value and corresponds to the VALUE attribute. This is a read-only property.

  • value is the current value. This starts out the same as the default value, but can be changed, either by the user or by JavaScript functions.

When you work with text fields, most of the time you will use the value attribute to read the value the user has entered or to change the value. For example, the following statement changes the value of a text field called username in the order form to "John Q. User":

document.order.username.value = "John Q. User"

Text Areas

Text areas are defined with their own tag, <textarea>, and are represented by the textarea object. There is one major difference between a text area and a text field: Text areas allow the user to enter more than just one line of information. Here is an example of a text area definition:

<textarea NAME="text1" ROWS="2" COLS="70">
This is the content of the TEXTAREA tag.

This HTML defines a text area called text1, with two rows and 70 columns available for text. In JavaScript, this would be represented by a text area object called text1 under the form object.

The text between the opening and closing <textarea> tags is used as the initial value for the text area. You can include line breaks within the default value.

Working with Text in Forms

The text and textarea objects also have a few methods you can use:

  • focus() sets the focus to the field. This positions the cursor in the field and makes it the current field.

  • blur() is the opposite; it removes the focus from the field.

  • select() selects the text in the field, just as a user can do with the mouse. All of the text is selected; there is no way to select part of the text.

You can also use event handlers to detect when the value of a text field changes. The text and textarea objects support the following event handlers:

  • The onFocus event happens when the text field gains focus.

  • The onBlur event happens when the text field loses focus.

  • The onChange event happens when the user changes the text in the field and then moves out of it.

  • The onSelect event happens when the user selects some or all of the text in the field. Unfortunately, there's no way to tell exactly which part of the text was selected. (If the text is selected with the select() method described above, this event is not triggered.)

If used, these event handlers should be included in the <input> tag declaration. For example, the following is a text field including an onChange event that displays an alert:

<input TYPE="TEXT" NAME="text1" onChange="window.alert('Changed.');">


The final type of form element is a button. Buttons use the <input> tag and can use one of three different types:

  • type=SUBMIT is a submit button. This button causes the data in the form fields to be sent to the CGI script.

  • type=RESET is a reset button. This button sets all the form fields back to their default value, or blank.

  • type=BUTTON is a generic button. This button performs no action on its own, but you can assign it one using a JavaScript event handler.

All three types of buttons include a NAME attribute to identify the button and a VALUE that indicates the text to display on the button's face. A few buttons were used in the examples in Hour 11, "Using Windows and Frames." As another example, the following defines a Submit button with the name sub1 and the value "Click Here":

<input TYPE="SUBMIT" NAME="sub1" VALUE="Click Here">

If the user presses a Submit or Reset button, you can detect it with the onSubmit or onReset event handlers, described earlier in this hour. For generic buttons, you can use an onClick event handler.

Check Boxes

A check box is a form element that looks like a small box. Clicking on the check box switches between the checked and unchecked states, which is useful for indicating Yes or No choices in your forms. You can use the <input> tag to define a check box. Here is a simple example:


Again, this gives a name to the form element. The VALUE attribute assigns a meaning to the check box; this is a value that is returned to the server if the box is checked. The default value is "on." The CHECKED attribute can be included to make the box checked by default.

A check box is simple: it has only two states. Nevertheless, the checkbox object in JavaScript has four different properties:

  • name is the name of the check box, and also the object name.

  • value is the "true" value for the check box—usually on. This value is used by the server to indicate that the check box was checked. In JavaScript, you should use the checked property instead.

  • defaultChecked is the default status of the check box, assigned by the CHECKED attribute.

  • checked is the current value. This is a boolean value: true for checked and false for unchecked.

To manipulate the check box or use its value, you use the checked attribute. For example, this statement turns on a check box called same in the order form:

document.order.same.checked = true;

The check box has a single method, click(). This method simulates a click on the box. It also has a single event, onClick, which occurs whenever the check box is clicked. This happens whether the box was turned on or off, so you'll need to examine the checked property to see what happened.

Radio Buttons

Another element for decisions is the radio button, using the <input> tag's RADIO type. Radio buttons are also known as option buttons. These are similar to check boxes, but they exist in groups and only one button can be checked in each group. They are used for a multiple-choice or "one of many" input. Here's an example of a group of radio buttons:

<input TYPE="RADIO" NAME="radio1" VALUE="Option1" CHECKED> Option 1
<input TYPE="RADIO" NAME="radio1" VALUE="Option2"> Option 2
<input TYPE="RADIO" NAME="radio1" VALUE="Option3"> Option 3

These statements define a group of three radio buttons. The NAME attribute is the same for all three (which is what makes them a group). The VALUE attribute is the value passed to a script or CGI program to indicate which button is selected—be sure you assign a different value to each button.


Radio buttons are named for their similarity to the buttons on old pushbutton radios. Those buttons used a mechanical arrangement so that when you pushed one button in, the others popped out.

As for scripting, radio buttons are similar to check boxes, except that an entire group of them shares a single name and a single object. You can refer to the following properties of the radio object:

  • name is the name common to the radio buttons.

  • length is the number of radio buttons in the group.

To access the individual buttons, you treat the radio object as an array. The buttons are indexed, starting with 0. Each individual button has the following properties:

  • value is the value assigned to the button. (This is used by the server.)

  • defaultChecked indicates the value of the CHECKED attribute and the default state of the button.

  • checked is the current state.

For example, you can check the first radio button in the radio1 group on the form1 form with this statement:

document.form1.radio1[0].checked = true;

However, if you do this, be sure you set the other values to false as needed. This is not done automatically. You can use the click method to do both of these in one step.

Like a check box, radio buttons have a click() method and an onClick event handler. Each radio button can have a separate statement for this event.

Drop-Down Lists

A final form element is also useful for multiple-choice selections. The <select> HTML tag is used to define a selection list, or a drop-down list of text items. The following is an example of a selection list:

<select NAME="select1" SIZE=40>
<option VALUE="choice1" SELECTED>This is the first choice.
<option VALUE="choice2">This is the second choice.
<option VALUE="choice3">This is the third choice.

Each of the <option> tags defines one of the possible choices. The VALUE attribute is the name that is returned to the program, and the text outside the <option> tag is displayed as the text of the option.

An optional attribute to the <select> tag, MULTIPLE, can be specified to allow multiple items to be selected. Browsers usually display a single-selection <select> as a drop-down list and a multiple-selection list as a scrollable list.

The object for selection lists is the select object. The object itself has the following properties:

  • name is the name of the selection list.

  • length is the number of options in the list.

  • options is the array of options. Each selectable option has an entry in this array.

  • selectedIndex returns the index value of the currently selected item. You can use this to check the value easily. In a multiple-selection list, this indicates the first selected item.

The options array has a single property of its own, length, which indicates the number of selections. In addition, each item in the options array has the following properties:

  • index is the index into the array.

  • defaultSelected indicates the state of the SELECTED attribute.

  • selected is the current state of the option. Setting this property to true selects the option. You can select multiple options if the MULTIPLE attribute is included in the <select> tag.

  • name is the value of the NAME attribute. This is used by the server.

  • text is the text that is displayed in the option. In Netscape 3.0 or later, you can change this value.

The select object has two methods—blur() and focus()—which perform the same purposes as the corresponding methods for text objects. The event handlers are onBlur, onFocus, and onChange, also similar to other objects.


You can change selection lists dynamically—for example, choosing a product in one list could control which options are available in another list. You can also add and delete options from the list.

Reading the value of a selected item is a two-step process. You first use the selectedIndex property, then use the value property to find the value of the selected choice. Here's an example:

ind = document.navform.choice.selectedIndex;
val = document.navform.choice.options[ind].value;

This uses the ind variable to store the selected index, then assigns the val variable to the value of the selected choice. You'll see an example script that uses this technique in Hour 21, "Improving a Web Page with JavaScript."

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020