Hypermedia Production Banner

JavaScript and Forms

I. Input and Output with Forms

Because all elements in HTML forms are exposed to JavaScript, you can use scripts to pass information to and from these elements, often without reloading the page. In many cases this is simply a matter of getting or setting the form element's value property, as in the example below:


After you've been warned about a null input condition, try typing something into the text box before you click the button.

The script associated with this form (triggered by an onClick handler within the Click Me button's <INPUT> tag) performs both read and write operations on the single text input of this form.

To read the current contents of that text box, we use a statement like this:

    someVariable = document.forms[0].elements[0].value;

As you can see from the familiar dot notation, JavaScript-enabled browsers generate a forms array with an entry for every form on the page, much like the images array. Unlike images, however, the forms array contains subsidiary levels of information: it has an array of elements in which each component may have several properties. In this case we access the value property of the first entry in the elements array of the first form on the page.

Every form element, whether an <INPUT></INPUT> container, a <TEXTAREA></TEXTAREA> container, or a <SELECT></SELECT> container, has a numbered entry in the elements array for its form. As in the case of images, numbers are assigned according to the form or element's appearance in the markup. The first form defined on the page is document.forms[0], the second is document.forms[1], etc., and the same logic applies to elements within the forms.

If we assign the current value of a text input to a variable, that variable automatically becomes a string variable. All strings have a length property, which lets us determine how many characters were entered.

To change the value or some other attribute of a form element, we simply perform an assignment using a statement like this:

    document.forms[0].elements[0].value = "boo";

The script blanks out the input box after 2 seconds by setting its value to "". (The delay is accomplished by a setTimeout command; view source for the details.)

II. Processing Selection Lists

Selection elements--sets of options deployed within <SELECT></SELECT> containers--need finer treatment in JavaScript, mainly because they are inherently more complicated.

Here's an example of a selection element, or pull-down menu, with a simple script attached as in the first example, via a button element. Click the button to see your selection from the menu in the text box at right.

Here's the script used to process the select element:

    function secondExample()
      {
        var getSelect = document.forms[1].elements[0];
        var theItem = 
          getSelect.options[getSelect.selectedIndex].text;
        document.forms[1].elements[1].value = theItem;
      }

As you can see, we begin by initializing a variable called getSelect (the name is arbitrary) and assigning the entire element to it. Note that this is not the same thing we did in the first example, where we simply extracted the text value from an input element. This move may seem a little hard to grasp conceptually, but it's absolutely necessary.

Once we've assigned the entire select element to a variable, we can then extract the property of that element in which we're interested, which happens to be the word or phrase on the line that was selected. To get to this information we have to use the options array which is generated automatically for every select element, and the selectedIndex property, which is also generated automatically and updated when the user makes a selection. Note that we have to use the variable to which we assigned the element, namely getSelect, twice in the dot notation. This makes sense if you think about it, and particularly if you realize that the select element is in effect an object.

The last line of the function is the familiar output statement, assigning the value at which we have arrived to the righthand text field.

III. Uses for JavaScript Form Processing

The most obvious reason to connect JavaScript and forms lies in pre-processing: catching confusing or inappropriate input. For instance, you might invoke a function that checks a two-letter abbreviation for the name of a U.S. state against an array containing the 50 official abbreviations. If there is a match, your pre-processing function would hand off execution to another script; if the user has typed a nonexistent abbreviation, you could display an alert box.

Consider some more ambitious and interesting applications as well. Using the indexOf() method of the string object (and the contents of all text input boxes and <TEXTAREA></TEXTAREA> containers are strings), you could look for the occurrence of certain words or phrases in user input. This technique could be used to construct text-adventure games. By scanning for punctuation marks and extracting certain key phrases you could produce artificial conversants ("bots") like Joseph Weizenbaum's famous ELIZA.

You might also use forms for display or output purposes. Since a form field may be updated without reloading the page, you could use scripting applied to a form as a means of introducing randomized, dynamic content. For an example of this application, see my simulated search query ticker. Code for this example may be downloaded from the directory ticker within productionShare on Crow.

Finally, consider this concept: the INPUT form element may have the type hidden, making it and its contents invisible. You can use a hidden form field to store data until the page is reloaded. You might use this feature to record some aspects of a user's interaction with the page, to contain a previous state of a field that is being edited, or in a more familiar vein, as a variation on the random-content trick.

The example below makes five random selections from a source array of 25 words without repeating any items. View the source for this page and examine the functions called randyVariation() and getRandomWord() to see the details and commented code.

Basically, these functions take a word from the source array and compare it to the contents of five invisible form fields. If the word occurs in any of these fields, a new random word is chosen. Once certified against previous use, the selected word is added to the top of the used-word stack (that is, written into the first of the invisible storage fields), and the values in the four fields below it are pushed down the stack (each one being assigned to the next higher-numbered field).

The logic of this procedure is essentially the same as that used in our previous examples of random selection, but this variation is a little easier to scale up than one that uses variables instead of fields. For one thing, it spares us having to write an if condition with five clauses.




University of Baltimore Logo
Copyright © 2000 Stuart Moulthrop