Tutorial 4 - Working with Forms

Tutorial 3 - Core Language - Tutorial 5 - Forms and DHTML

User interaction is commonly accomplished through the use of HTML forms and their input controls. Interaction involves acquiring data and then performing some task based on that information. The results can be presented either with dialogs or more commonly by using other input control elements.

As this tutorial relies heavily on their use, you should already be able to create HTML forms and include any input control in a functional layout. You may wish to refer to Quick Forms for a fast review of your skills or to my HTML forms reference page for more complete details.

Referencing Form and Control Objects

Forms can be designed to permit controlled (ie. prevalidated) data (eg. radio buttons, check boxes and select lists) or free format data such as text entry boxes and file uploads using input controls. These forms can be validated before submission using the techniques that are discussed in the next tutorial. The controls can also be used for input and output in client-side smart form utilities that are never submitted.

There are two techniques for referencing an input control object for reading or modifying it. The form method (old way) requires a surrounding form element and uses the format:

document.form_name.control_name

The element method (new way) of DOM object reference that requires no form element container is:

document.getElementById('control_id')

Use the form method (old way) when any of the following conditions apply:

  • many elements have to be passed to a single function.
  • radio controls or select boxes are used.
  • multiple field validations are to be done with arrays.
  • a form is required for CGI submission purposes.
  • Netscape 4 has to be supported.

Use the element method (new way) when:

  • XHTML specification is used!
  • the input controls are strictly for client-side use with no form submission and no support for Netscape 4 is offered. Removal of the form element helps suppress false submissions in some browsers. See the validation by entry topic for another technique that is used when a form is used.

Note: Netscape (and gecko engine based browsers) do not treat form objects in the same manner as MSIE and Opera. To them, forms are not globally accessible so either they are passed to the called function as an object or the specific value is passed. MSIE can access a form by using its specific name in the function. If you always pass the form through as a function parameter your routines will work in both sets of browsers! And it is better programming practice too!

Accessing Control Contents

Most controls can have their contents accessed or updated through the value property of the control's object. When used on the right side of an (equal's) assignment, the current value of the object is read. When used on the left side of an assignment, the object is updated. Exceptions to this general rule are:

Check Box
Use the checked property. The value is either true or false.
Radio Buttons
Use the checked property. The value is either true or false. Since all radio buttons in a group have the same name, the individual object is accessed via an index. Indexes are numbers in square brackets such as radioButton[0] etc. (NOTE: index numbering starts at zero with the first reference in the HTML document.)
Select List
The selectedIndex property holds the position in the list of the first currently selected item. A value of -1 indicates no selection has been made or it has been deselected.
form_name.control_name[form_name.control_name.selectedIndex].value reads the value (ie. what is assigned by the value attribute of the current selection.
form_name.control_name[form_name.control_name.selectedIndex].text reads the text (ie. what is contained in the option element) of the current selection.
Note: If multiple selections are allowed, you must cycle through the entire select control, testing the selected property of each item in the options array.
Note2: If you are trying to support the MSIE browser, use the multiple selection method, even if only one selection is allowed.
File
The file control uses FileUpload.value (note that the Object name is not the same as the type value - this is done to deliberately confuse programmers!)

Note: Although radio buttons are the most commonly indexed input control, any control can be set up for indexing by reusing (overloading) its name attribute in HTML. One appropriate use would be for gathering a column of numbers (perhaps scores or unit prices) in an array within a loop and doing totals or averages. The arrays always start at '0' and are accessed similar to the radio control example above.

Simple Text Control Example

Input text controls (single line) and textarea controls (multiple line) are commonly used to output the results of processing the input data. This example places the results of the system object Date method toString() into an input area. The input box is made readonly to prevent typing to it.

Since this is a simple action it can be done within the event call itself such as:

<input class="go130" type="button" value="Display date &amp; time"
   onclick="now=new Date;document.getElementById('t').value=now.toString();" />
<input name="t" type="text" readonly="readonly" />

However a more structured and easier to read approach is to separate the programming action into its own function that can be removed to the head section of the document (or even to a separate file). The activating event passes one control object to the called function so that it can be updated.

function showDate(thisObj) {
/* create a Date object using the system clock */
now=new Date;
/* convert contents to string and place in control */
document.getElementById(thisObj).value=now.toString();
}
................
<input type="button" value="Display date &amp; time"
   onclick="showDate('t')" />
<input id="t" type="text" readonly="readonly" />

Radio Button Confirmation Example

There are times when you may need to confirm that something has been read or an agreement made before access is given to a page. This can be done easily with a radio button control. Even more design elements (legend and fieldset) are included in this example. Note their effect.

Licence Agreement
I have read and accept this agreement Yes No

Here is the button setup and event call. For the complete form read the source file.

<input id="y" name="rbc" type="radio" />Yes
<input id="n" name="rbc" type="radio" checked="checked" />No
<input name="act" type="button" value="View Utilities"
 onclick="doYes(document.getElementById('y').checked)" />
</form>

And here is the JavaScript function. The === is important!

function doYes(entry) {
if (entry===true) {
    top.location.href="http://home.cogeco.ca/~ve3ll/utility.htm";
    } else {
    alert("Sorry - You must sign agreement to access utilities");
    }
}

Note: In this example I chose to pass only a simple data value rather than a control or complete form. It was sufficient for performing a test. However if feedback to a form control is needed, then the form or at least the control must be passed. Some programmers choose to always pass the form for consistency.

If you want this agreement to be remembered so that it doesn't have to be repeated, you will need to bake a cookie as described in the Cookies tutorial. If you need to log that an agreement was made, you will need to do a mailto submission as outlined in the Quick Forms tutorial. If you need security (ie. a concealed jump address) then check my Cryptology Zone for suggestions.

Select List Navigation Example

This example passes information gathered from a select control selection to an onclick event. Since the info contains URL's, the event is designed to perform the hyperlink jump.

<div class="c">
<table><<tr><th>select id="list">
<option selected value="javascript:alert('You must select from list')">
        Select a Tutorial...</option>
<option value="jstutor1.htm">1 - Screen Output</option>
<option value="jstutor2.htm">2 - Objects and Events</option>
... etc ...
</select>
</th><td>
<input type="button" value="Go To Site!" onclick="goto('list')" />
</td></tr></table></div>

The key to this example is the action contained in the onclick event. It takes the option highlighted in the select form and feeds its value to top.location.href for the jump. top.location is an object that refers to the location (ie. current web address) of the first document layer. href is a property that is the complete url within an object.

Note: The default selection (which is really a prompt) uses a JavaScript command to display a message rather than moving to a new document.

Once again the JavaScript component could (structured programmers would say should) be extracted to a separate function to enhance readability.

The property top.location.href can also be used in other ways to jump to a new HTML document. For example by using the system's date one could move on to other screens depending on the day of the week or hour of the day. It can also be used with browser sniffing (described in Forms and DHTML) to skip a page for specific browsers which do not support specific code on that page.

Dynamic Select Lists

This example illustrates passing multiple selected items from a select list to another select control. Only the select elements' names are passed through the onclick event. The add2list function finds the objects and loops through the options array looking for selected items. The function also prevents duplicate entries by maintaining a global picked array. Refer to the source listing head section. The form construction is:

<div class="c"><table class="n" summary="*"><tr>
<th class="n"><select name="list1" id="list1" size="10" multiple>
<option>1 - Screen Output</option>
<option>2 - Objects and Events</option>
... etc ...

</select></th>
<th class="n"><input class="go" type="button" value=" --> "
       onclick="add2list('list1','list2')" /></th>

<th class="n"><select name="list1" id="list2" size="10">
</select></th></tr></div>