Gathering Data with Forms in JavaScript


JavaScript form object

The first form in a document can be referred to as document.form1 ("form1" is the value of the NAME attribute of the form) or document.form[0].

Form object properties

  1. action - program to which for data will be submitted
  2. encoding - form MIME type (specified with the ENCTYPE attribute)
  3. length - number of form elements
  4. method - GET or POST
  5. target - window in which result of form (from the CGI script) will be displayed

Submitting & resetting forms

Use submit and reset buttons.

Detecting form events

There are two event handlers.

Scripting form elements

Both of the statements below refer to the first element called name1 on the form called order.

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

Text fields

INPUT TYPE="text" NAME="text1" VALUE="hello" SIZE="30"

JavaScript treats the INPUT TYPE shown above as a text object named text1.

document.order.username.value = 'Joe Soap'

The code above sets the text field username to Joe Soap.

Text field methods

Text field events

Buttons

INPUT TYPE="submit" NAME="sub1" VALUE="Click here"

The onClick event handler is commonly used with buttons.

Check boxes

INPUT TYPE="checkbox" NAME="check1" VALUE="yes" CHECKED>
document.order.check1.checked=true

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

Drop-down lists

SELECT NAME=="select1" SIZE=40>
OPTION VALUE="choice1" SELECTED> First choice
OPTION VALUE="choice2"> Second choice
OPTION VALUE="choice3"> Third choice

Drop-down list properties

Drop-down list methods

Drop-down list events

Reading the value of a select item is a two step process. First use the selectedIndex property to find the value of the selected choice.

ind = document.navform.choice.selectedIndex;
val = document.navform.choice.options[ind].value;
Displaying data from a form
Validating a form