Chapter 11. Forms and Form Elements


  • What the form object represents

  • How to access key form object properties and methods

  • How text, button, and select objects work

  • How to submit forms from a script

  • How to pass information from form elements to functions

Most interactivity between a web page and the user takes place inside a form. That's where a lot of the interactive HTML stuff lives for every browser: text fields, buttons, checkboxes, option lists, and so on.

In this chapter, we discuss how to locate forms and their controls in the document tree, how to change them, how to examine the user's input, and how to submit a form or suppress submission if the input doesn't validate.

The Form object

A form and the input controls that go inside it are DOM objects with unique properties that other objects in the document don't have. For example, a form object has an action property that tells the browser where to send input values when a form is submitted. A select control (drop-down list) has a selectedIndex property that tells us which option has been selected by the user.

Our first step is to point to the form on the page. Here are three ways of doing this, all referring to the following abbreviated snippet of a page that contains three forms:

<div id="header">
   <form id="search" action="...">...</form>
   <form id="join-list" action="...">...</form>
   <form id="contact" action="...">...</form>
  1. The DOM method getElementById(), as described in previous chapters, gives us a ...

Get JavaScript® Bible, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.