Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

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:

document.order.elements[0]
document.order.name1

By the Way

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.

You can also access form elements using the W3C DOM. In this case, you use an id attribute on the form element in the HTML document, and use the document.getElementById() method to find the object for the form. For example, this statement finds the object for the text field called firstname and stores it in the fn variable:

fn = document.getElementById("firstname");

This allows you to quickly access a form element without first finding the form object. You can assign an id to the <form> tag and find the corresponding object if you need to work with the form's properties and methods.

Did you Know?

See Hour 13, "Using the W3C DOM," for details on the document.getElementById() method.


Text Fields

Probably the most commonly used form elements are text fields. You can use them to prompt for a name, an 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 enable 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.
</textarea>

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 with the special character \n.

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 previously, 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.');">

Buttons

One of the most useful types 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 attribute that indicates the text to display on the button's face. A few buttons were used in the examples in Hour 10, "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 a 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:

<input type="CHECKBOX" name="check1" value="Yes" checked>

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 boxusually on. This value is used by server-side programs to indicate whether 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 in HTML.

  • 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 property. 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 a CGI program to indicate which button is selectedbe sure you assign a different value to each button.

By the Way

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.

Did you Know?

You can have more than one group of radio buttons on a page, and they will act independently. Assign a separate name attribute value to each group.


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.
</select>

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. The user 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.

The select object has two methodsblur() 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.

By the Way

You can change selection lists dynamicallyfor 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, and 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, and then assigns the val variable to the value of the selected choice. Things are a bit more complicated with a multiple selection: You have to test each option's selected attribute separately.

Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Part III: Learning More About the DOM
Hour 9. Responding to Events
Hour 10. Using Windows and Frames
Hour 11. Getting Data with Forms
The Basics of HTML Forms
Using the form Object with JavaScript
Scripting Form Elements
Displaying Data from a Form
Sending Form Results by Email
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Hour 12. Working with Style Sheets
Hour 13. Using the W3C DOM
Hour 14. Using Advanced DOM Features
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele