JavaScript and Forms Tutorial

This tutorial provides information on interacting with forms and form elements using JavaScript. Find out how to obtain references, get and set property values, and perform common tasks with various types of form controls. Topic areas include:

Referencing Forms and Form Elements in JavaScript
Presents traditional and modern approaches to obtaining references for handling forms.
JavaScript and Radio Buttons
Find out about radio buttons' onclick and onchange events, how to get the value of the selected radio button, how to get the value of a radio button onclick, and more.
JavaScript and Checkboxes
Find out how to handle checkboxes onclick, how to handle a group of checkboxes that share the same name, how to show/hide related content depending upon whether a checkbox is checked, and more.
JavaScript with Select and Option Elements
Find out how to get the value of the selected option or the list of multiple selections in a select box, how to handle the select element's onchange event, how to add and remove options, how to dynamically change the options in a select box based on the selection in another, and more.

Form HTML Attributes and JavaScript Properties

HTML attributes of forms and form elements are available as properties that can be accessed in JavaScript. For example, some of the more useful for JavaScript purposes are the type and value properties. The following demonstrates these as attributes specified in HTML and properties accessed via JavaScript:

<input name="firstName" type="text" value="John" />

<script type="text/javascript">
var fName = document.forms['demoForm'].elements['firstName'];
alert( fName.value ); // John
alert( fName.type ); // text

However, not all properties have a corresponding HTML attribute. For example, textarea and select elements do not have a type attribute, but do have a type property.[1] Textarea and select elements do not have a value attribute either, but they do have a value property.[2]

Also, each form element has a form property that is a reference to the form containing it. Forms have an elements property that is an array-like HTMLCollection containing references to all of the form elements contained within it. This elements property has a length property specifying how many elements are in the form.

Examples throughout this tutorial demonstrate the most commonly used properties for that form element. Visit the topic areas listed above to see.

  1. Textareas have the type textarea; select elements have a type of either select-one or select-multiple depending upon whether the multiple attribute is included. ^
  2. The value property of a textarea is the element's content. See more information on determining the value of select-one and select-multiple type select lists. ^