home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

15.2. Defining Form Elements

HTML form elements are the primitive objects with which we create graphical user interfaces for our JavaScript programs. Figure 15-1 shows a complex form that contains at least one of each of the basic form elements. In case you are not already familiar with HTML form elements, the figure includes a numbered key identifying each type of element. We'll conclude this section with an example (Example 15-1) that shows the HTML and JavaScript code used to create the form pictured in Figure 15-1 and to hook up event handlers to each of the form elements.

Figure 15-1

Figure 15-1. HTML form elements

Table 15-1 lists the types of form elements that are available to HTML designers and JavaScript programmers. The first column of the table names the type of form element, the second column shows the HTML tags that are used to define elements of that type, and the third column lists the value of the type property for each type of element. As we've seen, each Form object has an elements[] array that contains the objects that represent the form's elements. Each of these elements has a type property that can be used to distinguish one type of element from another. By examining the type property of an unknown form element, JavaScript code can determine the type of the element and figure out what it can do with that element. (We'll see this done in Example 15-2, at the end of the chapter.) Finally, the fourth column of the table provides a short description of each element and also lists the most important or most commonly used event handler for that element type.

We'll talk more about form elements later in this chapter. Complete details about the various types of elements are available in the client-side reference section, under the name listed in the first column of Table 15-1. Although each type of form element has a separate reference page, note that most of the elements are created with HTML <input> tags and are, in fact, all Input objects. The client-side reference page named "Input" lists the features that all these elements have in common, and the type-specific pages provide specific details about working with a particular type of form element. Note that the names Button, Checkbox, and so on from the first column of the table may not correspond to any actual object in a client-side JavaScript implementation, and note also that the DOM standard does not define any interfaces with these names. Still, each type of form element has a distinct appearance and distinct behavior, and it is useful to treat them as separate types, at least for the purposes of the client-side reference section. In the DOM reference section you can find material about forms and their elements under the names "HTMLFormElement," "HTMLInputElement," "HTMLTextAreaElement," "HTMLSelectElement," and "HTMLOptionElement."

Table 15-1. HTML form elements


HTML tag

type property

Description and events


<input type="button"> or <button type="button">


A push button; onclick.


<input type="checkbox">


A toggle button without radio-button behavior; onclick.


<input type="file">


An input field for entering the name of a file to upload to the web server; onchange.


<input type="hidden">


Data submitted with the form but not visible to the user; no event handlers.




A single item within a Select object; event handlers are on the Select object, not on individual Option objects.


<input type="password">


An input field for password entry -- typed characters are not visible; onchange.


<input type="radio">


A toggle button with radio-button behavior -- only one selected at a time; onclick.


<input type="reset"> or <button type="reset">


A push button that resets a form; onclick.




A list or drop-down menu from which one item may be selected; onchange. (See also Option object.)


<select multiple>


A list from which multiple items may be selected; onchange. (See also Option object.)


<input type="submit"> or <button type="submit">


A push button that submits a form; onclick.


<input type="text">


A single-line text entry field; onchange.




A multiline text entry field; onchange.

Now that we've taken a look at the various types of form element and the HTML tags used to create them, Example 15-1 shows the HTML code used to create the form shown in Figure 15-1. Although the example consists primarily of HTML, it also contains JavaScript code used to define event handlers for each of the form elements. You'll notice that the event handlers are not defined as HTML attributes. Instead, they are JavaScript functions assigned to the properties of the objects in the form's elements[] array. The event handlers all call the function report( ), which contains code that works with the various form elements. The next section of this chapter explains everything you need to know to understand what the report( ) function is doing.

Example 15-1. An HTML form containing all form elements

<form name="everything">                   <!-- A one-of-everything HTML form... -->
 <table border="border" cellpadding="5">   <!-- in a big HTML table -->
     <td>Username:<br>[1]<input type="text" name="username" size="15"></td>
     <td>Password:<br>[2]<input type="password" name="password" size="15"></td>
     <td rowspan="4">Input Events[3]<br>
       <textarea name="textarea" rows="20" cols="28"></textarea></td>
     <td rowspan="4" align="center" valign="center">
       [9]<input type="button" value="Clear" name="clearbutton"><br>
       [10]<input type="submit" name="submitbutton" value="Submit"><br>
       [11]<input type="reset" name="resetbutton" value="Reset"></td></tr>
     <td colspan="2">
       Filename: [4]<input type="file" name="file" size="15"></td></tr>
     <td>My Computer Peripherals:<br>
       [5]<input type="checkbox" name="peripherals" value="modem">56K Modem<br>
       [5]<input type="checkbox" name="peripherals" value="printer">Printer<br>
       [5]<input type="checkbox" name="peripherals" value="tape">Tape Backup</td>
     <td>My Web Browser:<br>
       [6]<input type="radio" name="browser" value="nn">Netscape<br>
       [6]<input type="radio" name="browser" value="ie">Internet Explorer<br>
       [6]<input type="radio" name="browser" value="other">Other</td></tr>
     <td>My Hobbies:[7]<br>
       <select multiple="multiple" name="hobbies" size="4">
         <option value="programming">Hacking JavaScript
         <option value="surfing">Surfing the Web
         <option value="caffeine">Drinking Coffee
         <option value="annoying">Annoying my Friends
     <td align="center" valign="center">My Favorite Color:<br>[8]
       <select name="color">
         <option value="red">Red        <option value="green">Green
         <option value="blue">Blue      <option value="white">White
         <option value="violet">Violet  <option value="peach">Peach

<div align="center">        <!-- Another table--the key to the one above -->
  <table border="4" bgcolor="pink" cellspacing="1" cellpadding="4">
      <td align="center"><b>Form Elements</b></td>
      <td>[1] Text</td>  <td>[2] Password</td>  <td>[3] Textarea</td>
      <td>[4] FileUpload</td> <td>[5] Checkbox</td></tr>
      <td>[6] Radio</td>  <td>[7] Select (list)</td>
      <td>[8] Select (menu)</td>  <td>[9] Button</td>
      <td>[10] Submit</td>  <td>[11] Reset</td></tr>

// This generic function appends details of an event to the big Textarea
// element in the form above. It is called from various event handlers.
function report(element, event) {
    var elmtname = element.name;
    if ((element.type == "select-one") || (element.type == "select-multiple")){
        value = " ";
        for(var i = 0; i < element.options.length; i++)
            if (element.options[i].selected) 
                value += element.options[i].value + " ";
    else if (element.type == "textarea") value = "...";
    else value = element.value;
    var msg = event + ": " + elmtname + ' (' + value + ')\n';
    var t = element.form.textarea;
    t.value = t.value + msg;

// This function adds a bunch of event handlers to every element in a form.
// It doesn't bother checking to see if the element supports the event handler,
// it just adds them all. Note that the event handlers call report( ) above.
// Note that we're defining event handlers by assigning functions to the
// properties of JavaScript objects rather than by assigning strings to
// the attributes of HTML elements.
function addhandlers(f) {
    // Loop through all the elements in the form
    for(var i = 0; i < f.elements.length; i++) {
        var e = f.elements[i];
        e.onclick = function( ) { report(this, 'Click'); }
        e.onchange = function( ) { report(this, 'Change'); }
        e.onfocus = function( ) { report(this, 'Focus'); }
        e.onblur = function( ) { report(this, 'Blur'); }
        e.onselect = function( ) { report(this, 'Select'); }

    // Define some special-case event handlers for the three buttons:
    f.clearbutton.onclick = function( ) {
        this.form.textarea.value=''; report(this,'Click');
    f.submitbutton.onclick = function ( ) {
        report(this, 'Click'); return false;
    f.resetbutton.onclick = function( ) {
        this.form.reset( ); report(this, 'Click'); return false;
// Finally, activate our form by adding all possible event handlers!

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.