ability to use the Web browser's GUI (Graphical User Interface) to create small programs very quickly is quite compelling.
Another example might be for you to create an order form that checks that all of the order fields are filled in correctly and even calculates a running total of the cost of the items ordered (see fig. 6.2).
Figure 6.2 : Another Web site, with an order form that automatically calculates your total order.
review the various HTML tags that allow you to create a form.
Although you may already be familiar with these tags, it is good
to review them in case you discover features you may not be taking
advantage of currently. Table 6.1 summarizes these tags.
|<FORM ACTION="URL" METHOD="GET"></FORM>||Defines a form|
|<FORM ENCTYPE="multipart/form-data"></FORM>||Uploads a file via a form|
|<INPUT TYPE="TEXT">||Input field|
|<INPUT NAME="somename">||Field name|
|<INPUT VALUE="somevalue">||Field value|
|<INPUT SIZE=6>||Field size (in characters)|
|<INPUT MAXLENGTH="100">||Maximum length of field|
|<SELECT NAME="somename">||Selection list name|
|<SELECT SIZE="6">||Number of options in list|
|<SELECT MULTIPLE>||Multiple selections (more than one)|
|<OPTION SELECTED>||Default Option|
|<TEXTAREA ROWS="5" COLS="5">...</TEXTAREA>||Text area input box size|
|<TEXTAREA NAME="somename">...</TEXTAREA>||Text area name|
|<TEXTAREA WRAP=OFF>||Wraps the text|
These tags must begin and end your form.
The following are attributes of the FORM and /FORM tags:
This tag creates various input fields. For example, the following:
allows you to establish an input field for addresses within the form.
Pairing this tag with the following attributes allows you to manipulate specific field designations:
<INPUT NAME="thisimage" TYPE="IMAGE" SRC="foo.gif" ALIGN="TOP">
Figure 6.4 : HTML source code of the input fields in figure 6.3.
These tags present either a scrolling list of choices or a pop-up menu. <SELECT> is generated in different ways, based on your choice of options. You can generate a single window that "pops open" to reveal all of the options-from which you can then select one-or you can see a scrolling list of options with up and down arrows much like a regular window-which allows you to see many choices at once. Pull-down windows are best for times when you want someone to choose one option, and it saves screen space. It's best when the number of options are fewer than five or so. If you have more than five, you should set the SIZE attribute to show the first five (or less) and allow the user to scroll through the rest.
The following lists the attributes you use with <SELECT>. Try out many variations on a test Web page to see how changing the attributes changes the way the list is shown:
An often underutilized way to use this form element is to place a caption to an image just under the image with <SELECT SIZE=1> and the caption text inside-one line to an <OPTION>.
The result is a nice "pop-open" caption that allows you to use that saved space in other ways. Note though that the bar will be as wide as your longest line in the <OPTION> list.
Contained within the SELECT and /SELECT tags, this tag designates a selectable item. The following list describes the attributes an <OPTION> might have:
These tags provide an area for a user to enter multiple lines of text. This defaults to four rows in length, with each row 40 characters wide. The following list describes each attribute you might use in a TEXTAREA tag:
Listing 6.1 form Attributes
<FORM NAME = "formname" TARGET = "windowname" ACTION = "serverURL" METHOD = GET | POST ENCTYPE = "encodingType" [ onSubmit = "handlerText" ] > </FORM>
The new attributes you might notice are TARGET and onSubmit. TARGET specifies the window that the responses go to. The event handler onSubmit is optional. The text listed in the handlerText is evaluated when you submit this form via the SUBMIT button or use the submit method in another part of your script.
Once you have created this object, you can address its properties and methods in the following way:
<form name="thisform"> <input type=text name="input1" value="hi there!"> </form>
By doing this you create an object called thisform which also exists as document.forms.
You can access individual fields in this form-where you can either read that field directly or send a new value to that field-which might (depending on the type of input field) dynamically change on the screen. To access information about this form, use the following naming conventions:
For an example, take a look at listing 6.2.
Listing 6.2 Example of Accessing a form Element
The return of listing 6.2 is the following:
<INPUT TYPE = "button" NAME =" nameInside" VALUE = "nameOnButton" [onClick = "handlerText"]>
This is an extremely useful object, and you will probably find yourself using this often to create buttons to run scripts, open new windows, or even cause the browser to leave your Web site altogether! You must use this inside a set of FORM.../FORM tags. You access a button's properties and methods in the following way:
For example, listing 6.3 creates a page that looks like figure 6.8. Upon clicking the button, you will see an Alert dialog box that looks like figure 6.9.
Figure 6.8 : Web page with alert button example.
Figure 6.9 : Here's the alert!.
Listing 6.3 Using a Button form Element in
You can access the properties of the button object in listing 6.3 by using one of the following:
If you want to retrieve the name of the button as a string object, you could use either of the examples below, which would return "Click Me!":
Once you have created a button object you can change its value, but the text on the button does not change to reflect this. This is because the button was written to the screen when the page was loaded and cannot be changed unless the page is reloaded. And reloading the page alone does not implement the change, since the button reverts to its default value in the HTML code when it is reloaded. The only way to change this value is to set the value equal to some variable that can persist across page reloading. For more information on how to do this, see chapter 12, "More About Java."
The checkbox Object The checkbox object is created inside a form and appears as a small box with or without a mark (usually an x) inside it. Think of a checkbox as an On/Off switch.
A user can flip this switch on or off by clicking his mouse inside this box. Clicking here can also trigger an onClick event in your script. You create a checkbox via the syntax in listing 6.4.
Listing 6.4 checkbox Object
<INPUT TYPE = "checkbox" NAME = "checkboxName" VALUE = "checkboxValue" [CHECKED] [onClick = "handlerText"]> textToDisplay
Accessing the properties of this object is very similar to accessing the properties of the button object. The properties are as follows:
Listing 6.5 is an example of using the checkbox object in a script (see fig. 6.10).
Figure 6.10: Web page with checkbox.
Listing 6.5 Using the checkbox Object
When you click the checkbox so that it is checked, you will see something like what is shown in figure 6.11. If you then "uncheck" it, you will see an alert box like that shown in figure 6.12.
Figure 6.11: Once the checkbox is checked, you see this alert.
Figure 6.12: Clicking the checkbox off will give you this alert.
The radio Object This object allows a user to make a choice of a single selection from many. Usually this is a list of related items from which you wish the user to pick only one choice.
The radio object is very similar to the checkbox
object, except that a series of
radio objects with the same NAME attribute toggle all of the radio buttons off except for the one that was picked. In other words, when you click one radio button in a group of related buttons, all of them will be off except for the one you clicked. You create a radio object using the syntax in listing 6.6.
Listing 6.6 radio Object Syntax
<INPUT TYPE="radio" NAME = "radioName" [CHECKED] [onClick = "handlerText"]> textToDisplay
Accessing information from the radio object is slightly different than from the checkbox object. Since all of the radio buttons of a given group have the same NAME attribute, you access individual radio buttons by adding an index value to the NAME. The format for doing this is as follows:
Figure 6.13: Web page example of using radio buttons to constrain user input.
Listing 6.7 Radio Button Example
<form name = "game"> <input type = "text" name="output" size=15> <input type = "radio" name="choice" value = "rock" onClick ="game.output.value='The Rock'">The rock <input type = "radio" name="choice" value= "scissors" onClick ="game.output.value='The Scissors'">The scissors <input type = "radio" name="choice" value = "paper" onClick = "game.output.value='The Paper'">The paper </form>
This piece of code allows a user to pick one of the three choices-rock, paper, or scissors-which then shows up in the text field box. If the user wants to choose a fourth alternative, say bomb, then she just has to type it in to the box. This is a quick way for you to offer both a series of preset choices, as well as allow a user to place her own customized choice.
The hidden Object Often when you create an interactive form, you want to keep some information hidden, yet still pass this information on to the server when the form is submitted. This is often information about the user-perhaps when he last accessed your page, or some preference that he had set in the previous form that generated this one. You can keep track of this information with hidden fields. This field is often used in place of Netscape's "cookies" for compatability to browsers that do not support the cookie specification. Hidden fields contain text information and are not displayed on the screen with the rest of the form.
Netscape cookies are small strings of text stored in your cookies.txt file. They are often used to store information about you or your computer that is used by various sites to "remember" some bit of information about you between visits to that Web site. The server writes this code to your machine and will reread it when you visit again. Although this feature is very useful, there are still debates as to its security and validity of use.
To create a hidden object, use the following syntax:
<INPUT TYPE="hidden" NAME="hiddenName" [VALUE = "textValue"]>
You can access the properties of this object by using the following:
For example, the following returns "hi there!":
<form> <input type=hidden name=hideme value="hi there!"> </form> document.write(hideme.value);
When you use hidden fields, it adds a sense of "state" to the Web. What this means is that usually a Web site has no real way of knowing if a visitor to that Web site had just been there moments ago, or if he is visiting for the first time. Using the hidden field, you can place a hidden reminder to yourself (you as the Web site) on the page he receives-such as a timestamp-and retrieve that reminder whenever he submits that form to you for more information. This is very similar to the process one might go through to enter a parking lot, pick up a tag, then return that tag when you leave. Your server can read that hidden field into a CGI script and respond to the user of the page with something like "Welcome Back! Here's what's changed since you were here last!" Another use might be that of a hidden field in a Web-based game which stores the current score, location, and state of a player. This information is sent back to the game engine every time the player moves to a new location.
<INPUT TYPE="password" NAME = "passwordName" SIZE=integer [VALUE = "textValue"]>
Accessing the properties and methods of this object once it is created is identical to previous examples and is as follows:
The password object uses the focus, blur, and select event handlers as methods. Let's say you want to check the validity of a password before a user actually sends it back to the server for a login. You can create a function that checks the password and notifies the user if he entered an invalid password. See listing 6.8 for an example.
Listing 6.8 Form Validation Example
Don't confuse the password object with the hidden object. The password object conceals what a user types in to a text entry field, while a hidden object simply hides the whole field. Both input types in some way hide information.
The text Object The text input field in an HTML document is your workhorse for inputting many types of information. Most other types of input in forms are derivations of this kind of input.
Listing 6.9 text Object Syntax
<INPUT TYPE="text" NAME="textName" VALUE = "textValue" SIZE = integer [onBlur = "handlerText"] [onChange = "handlerText"] [onFocus = "handlerText"] [onSelect = "handlerText"]>
A real-world example of this would be the following:
<FORM> <INPUT TYPE="text" NAME="todaysdate" VALUE="" SIZE="5" onBlur=" getDate()" onChange="setDate()" onFocus="alert('Set the date')" onSelect="alert('Really change?')"> </FORM>
The text object properties reflect the information you provide in the tag when you create the object. Table 6.2 is a listing of those properties with an example of how you would access them.
|defaultValue||myText.defaultValue||The value of the input tag at page load time|
|name||myText.name||The NAME argument|
|value||formName.elements.value||The VALUE argument|
You can act on this object in a number of ways, either indirectly by another function, or directly by using the event handlers contained in the object. Tables 6.3 and 6.4 list the methods and event handlers associated with the text object.
|focus||myText.focus()||Equivalent to clicking this field|
|blur||myText.blur()||Equivalent to clicking another field after using this one|
|select||myText.select()||Equivalent to dragging the mouse across all the text in this field-selecting it|
|onBlur||<input type=text onBlur="alert('blur!')">||Runs "alert()" when focus leaves this field|
|onChange||<input type=text onChange="alert('changed')">||Runs "alert()" if the text has changed whenfocus leaves this field|
|onFocus||<input type=text onFocus="alert('start typing!')">||Runs "alert()"when user clicks in (or other-wise gives focus to)this field.|
|onSelect||<input type=text "alert('text selected!')">||Runs "alert()" once onSelect =some text in this field is selected|
The script in listing 6.10 places information about a link in a text field below a series of links when a user passes the mouse over each link. This illustrates how you can use other event handlers to pass information to a text field (see fig. 6.14).
Figure 6.14: Using onMouseOver, you can display different text in a text field.
Listing 6.10 Event Handlers and Text Fields
As you pass your mouse over each link-one, two, or three-you see that the text in the text field changes as well. You can easily modify this code to display helpful information about links on your own page beyond the URL that displays at the bottom left of the Netscape Navigator (which is called the status area).
Listing 6.11 textarea Object Syntax
<TEXTAREA NAME ="textareaName" ROWS = integer COLS = integer WRAP = on|off|physical|virtual [onBlur = "handlerText"] [onChange = "handerText"] [onFocus = "handlerText"] [onSelect = "handlerText"]> textToDisplay </TEXTAREA>
A textarea object uses essentially the same attibutes, methods, and properties as does the text object (see tables 6.2, 6.3, and 6.4). You can provide default text to display in this field by adding text between the TEXTAREA.../TEXTAREA tags.
Long Example: Foobar the Bazbarian I use the
textarea input field in a game I wrote called Foobar
the Bazbarian. In this game, the user can click buttons to go
north, south, east, and west, and pick up various objects along
the way to eventually win the game. The game itself is very simple
in its concept, and is long in implementation only because of
the many pieces of text input that can be displayed in the textarea
window. In a way, this completely turns around the concept of
a textarea from one in which you require a user to input long
lines of text to displaying something like a miniature computer
terminal. Listing 6.12 shows this program's code and figure 6.15
provides a sample display of how it might look on a Web page.
Figure 6.15: Web page view of Foobar the Bazbarian.
Listing 6.12 Foobar the Bazbarian
<INPUT TYPE="submit" NAME="submitName" VALUE="buttonText" [onClick = "handlerText"]>
You access this object's properties and methods by the following syntax:
When you click a submit button, it always loads a new page-even if that page is the same page you were already on. This is useful in that you can use a form to change attributes of the current page and see them change when you submit the form. The submit object uses the onClick event handler and can be clicked by using the submitName.click method.
<INPUT TYPE="reset" NAME="resetName" VALUE="buttonText" [onClick ="handlerText"]>
To access its methods and properties, you use the same familiar syntax, as follows:
The reset button uses the same onClick event handler and click method as the submit object.
A Simple Form Validation Example Listing 6.13 is a simple script that checks all of your input to see that you have placed the correct information inside each field. It then submits the form.
Listing 6.13 Form Input Validation Example
From the example in listing 6.13, you can see how an input of type button was used in place of an input of type submit. In a real-world script, you could either use a button input type with an onClick event handler which would then run a check on that specific field, or you could keep the submit button and use an onSubmit event handler to run checks on all of the input fields at once. The difference here is that when you use onClick and the button, you can be more specific as to which area you are checking; whereas, using the more general onSubmit, you can check all the fields at once without asking the visitor to check them.