If you have been reading this book through to this point, you have proven that you have more than just a casual interest in JavaScript (unless, of course, you've happened to open the book to this page while you are in the book store!). This chapter continues with the "object" theme of this part of the book and introduces you to interactive HTML objects. They are interactive in that they allow you to respond in some way to input from someone who visits your site.
When you finish this chapter, you should be well on your way to building your first set of JavaScript scripts for your site. Most of the sites that you find today were built using many of the concepts in this chapter. The ability to use forms to lay out input and output areas; buttons to accept questions, replies, or other input; and "back end" JavaScript to interpret that input, you have the beginnings of a full-fledged application. The
ability to use the Web browser's GUI (Graphical User Interface) to create small programs very quickly is quite compelling.
What you should take from this chapter is the knowledge of building forms, as well as having a new view of forms. Before JavaScript, the form was basically just for typing in responses to questions, or making a selection among some choices. Now, the form can be a template that instantly responds to some action on your Web site vistor's part.
JavaScript is one of the first scripting languages that applies an object-oriented approach (via its roots in Java) to writing and modifying Web pages. JavaScript takes expressions in HTML, such as
<A HREF="http://www.yahoo.com">Yahoo!</A>
and creates an object with methods and properties similar to the ones you read about in chapter 5, "Built-In JavaScript Objects."
This chapter and the next take you through the objects in JavaScript that are created and used when you write HTML code-specifically those related to working with HTML forms. Forms provide a key way for you to build a user interface with which you can create miniature "applettes." An example of this is to use HTML forms buttons and text boxes to allow a user to click buttons on a calculator and see the results immediately (see fig. 6.1). (I use the term applettes as an alternative to Java's applet-which is a small program that runs on your browser. JavaScript scripts are smaller, yet might perform many of the same tasks you see in Java. Thus, you can think of them as mini-applets.)
Figure 6.1 : A Web site using a calculator in JavaScript.
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.
Before JavaScript, the process of creating and validating information that a user entered via a form depended heavily on sending and receiving information from a server-side CGI script. A CGI was possibly used for creating the actual form (generating HTML), validating the information (such as checking that all of the fields were filled in correctly), and sending a response back to the user confirming that the information had been sent successfully.
Using JavaScript, you can place much of the work on the client-side, which can reduce dramatically the connection times between the client (the Navigator) and the server (your Web server). In terms of validating form information, you do this by allowing the script to inspect the contents of each field that the user has entered and present an alert to the user if the information does not meet some specific requirements-like too many characters or if the field is empty.
Before we delve into the secrets of JavaScript and forms, let's
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.
Tag | Meaning |
<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 CHECKED> | Checked |
<INPUT SIZE=6> | Field size (in characters) |
<INPUT MAXLENGTH="100"> | Maximum length of field |
<SELECT></SELECT> | Selection list |
<SELECT NAME="somename"> | Selection list name |
<SELECT SIZE="6"> | Number of options in list |
<SELECT MULTIPLE> | Multiple selections (more than one) |
<OPTION>sometext | Option |
<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:
<INPUT NAME="Address">
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:
TIP |
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:
This section introduces you to JavaScript's HTML objects that relate to forms. With each of these objects, you will see further how to build a form that will be able to respond instantly to user input.
You will learn about buttons, checkboxes, and radio buttons. These form elements consist of all the "clickable" elements. Mouse clicks on these elements can be used to trigger JavaScript functions, or to submit a form to either your home server or another script running elsewhere (perhaps in another frame or window). You will get quite a bit of mileage out of these elements, and JavaScript has enhanced them with its ability to monitor their status (such as if a radio button is on or off).
Now that you've had a brief refresher of the different HTML tags that build a form, you are ready to begin using JavaScript to bring new life to your forms. We will examine how JavaScript builds special objects as it reads your HTML code and explore how to use these objects to create an interactive form.
The form Object Whenever you declare a <FORM>...</FORM> in your Web page, JavaScript takes the information contained within that form and builds a form object. To create a form object, use the syntax in listing 6.1.
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:
JavaScript places each form it finds in a page in an array called forms. You can access each form by either its index in this array (with the first form at 0, the next at 1, and so on) or by its name. For example,
<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[0].
Figure 6.7 illustrates a review of the object hierarchy to display where a form object lies in relation to the other objects generated by JavaScript.
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
in JavaScript
<script language="javascript"> <form name="thisForm" action="foo.html" ENCTYPE="text/ascii" method="GET"> </form> <!-- hide this code document.forms[0].method = "POST' document.write(document.thisForm.method) --> </script>
The return of listing 6.2 is the following:
POST
The button Object The button object is a new type of INPUT tag that allows you to create general purpose buttons in a form. You can use these buttons to activate any function, or to open a new URL, or perform any other action that JavaScript can initiate. To define a button object use the following syntax:
<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
JavaScript
<script language="JavaScript"> <!-- hide me from other browsers function hey() { document.alert("Hey there! You pushed the button!") } // end hiding from other browsers --> </script> <form> <h1>Click below for an alert!</h1> <input type="button" name="alertbutton" value="Click Me!" onClick="hey()"> </form>
You can access the properties of the button object in listing 6.3 by using one of the following:
document.forms[0].elements[0].name
or
alertbutton.name
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!":
document.forms[0].elements[0].value
or
alertbutton.value
NOTE |
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
<html> <script language="javascript"> function mystatus(){ (document.theForm.theCheckbox.checked) ? alert("The box is checked") : alert("The box is not checked! Oh no!") } </script> <form name="theForm"> <input type="checkbox" name="theCheckbox" value="myValue" onClick="mystatus()"> </form> </html>
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:
You can click a specific radio button in JavaScript by using the following:
radioName[index1].click
Listing 6.7 is an example of using radio buttons with JavaScript. The result is shown in figure 6.13.
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.
This section gives you experience working with the text-based input fields in an HTML form, and shows how you can use JavaScript to enhance these input fields' usefulness to you as a script writer.
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.
The password Object The password input field in a form is very useful for those times when you need to create a logon screen and keep the password of that logon hidden from view or from being printed by some malicious user who sees the login screen. Any time you want the information hidden from sight as a user types that information on the screen, use the password input field. To create this as an object in JavaScript, use the following syntax:
<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
<script language="JavaScript"> function checkPass(mypass) { if(notpass) { alert ("You have entered an invalid password. Try again.") mypass.focus() mypass.select() } function not <form onSubmit="checkPass(this)"> <input type="password" name="mypass"> </form>
NOTE |
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.
The text input field is simply a small box of a set size that contains a cursor when you click it. It allows a user using the form to type in information such as a name, a date, or any other kind of information. If the text a user types is too long for the box, it scrolls to the left to accomodate the additional text. In JavaScript, this field serves a new and exciting purpose. Not only can a user using the form enter information into this field, but the script itself can enter information as well. In chapter 5 you saw a script that used this field to display a constantly changing digital clock.
You create a JavaScript text object using the syntax in listing 6.9.
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.
Property | Example | Description |
defaultValue | myText.defaultValue | The value of the input tag at page load time |
name | myText.name | The NAME argument |
value | formName.elements[0].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.
Method | Example | Description |
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 |
Event Handler | Example | Description |
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
<script language = "javascript"> <!-- hide from other browsers var num =0 function showLink(num){ if (num==1) {document.forms[0].elements[0].value= "one"; } if (num==2) {document.forms[0].elements[0].value = "two"; } if (num==3) {document.forms[0].elements[0].value = "three"; } } // stop hiding --> </script> <form> <input type=text size=60 > </form> <a href="#" onMouseOver="showLink(1)">one</a><br> <a href="#" onMouseOver="showLink(2)">two</a><br> <a href="#" onMouseOver="showLink(3)">three</a><br>
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).
The textarea Object When you need a user to input more than just one line of text in a form you use the textarea input type. This is the case if you are providing to the user an e-mail feedback form and want to allow space for the user to type in a lengthy note. To create a textarea object in JavaScript, use the syntax shown in listing 6.11.
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
<HTML> <HEAD> <TITLE>FOOBAR! The Bazbarian</TITLE> </HEAD> <BODY > <script language="JavaScript"> <!-- The Engine //variable declarations var location="0" var locDesc= new StringArray(16) var zero=0 var bonus="10" locDesc[0]='You are standing at the edge of a small island. Palm trees sprout everywhere and obscure your view to the East and South. The beach is bordered on the North and West' locDesc[1]='The beach is to the West. You see the remains of your wrecked ship here. The forest is to the East and the beach goes North and South.' locDesc[2]='The beach is West of you. At the edge of the forest stands a silver cage with a beautiful princess who becons for you to unlock the cage.' locDesc[3]='The beach lapps at you from the West and South. The palm trees to the North and East sway in the wind. You hear screaming to the North.' locDesc[4]='The ocean borders the North. On the beach you see empty coke cans and various other washed up trash. ' locDesc[5]='You are surrounded by palm trees. A monkey waves a you. You hear screaming to the South.' locDesc[6]='In a clearing, you see a golden cage with a georgeous princess waving at you. She begs you to find the key and let her free.' locDesc[7]='The beach borders to the South. There are graves here with names of other warriors like yourself who failed...' locDesc[8]='The beach borders the North end of the island. The wind blows fiercer here.' locDesc[9]='You are in the midst of palms. Footprints dot the sand in all directions.' locDesc[10]='A woman screams to the West. Sharp rocks hurt your bare feet as you wander...' locDesc[11]='The beach borders the Southern end of the island. You hear a strange sound to the East, like a storm in the distance.' locDesc[12]='You see a chest full of gold, jewels and many other things. Your search reveals....' locDesc[13]='The beach stops you short to East. There are the remains of a campfire here.' locDesc[14]='Bones litter the beach to the East. They look human. You hear a sound like rushing wind to the South. Palms trees obscure your view.' locDesc[15]='A large green Dragon turns to look at you as you enter the clearing. Its growl is like a Mac Truck stuck in high gear.' // functions function StringArray (n) { this.length = n; for (var i = 1; i <= n; i++) { this[i] = '' } return this } function initgame(){ var intro = "Welcome to Foobar the Bazbarian! \r\nClick on buttons to navigate\r\nClick RESET to start over\r" document.forms[0].dialogbox.value=intro+locDesc[0] document.forms[5].score.value=zero document.forms[5].itemhere.value="None" document.forms[5].your1.value="Empty" document.forms[5].your2.value="Empty" document.forms[5].your3.value="Empty" document.forms[5].your4.value="Empty" location=0 } function upscore(addscore){ oldscore=document.forms[5].score.value; num1=parseFloat(addscore); num2=parseFloat(oldscore); newscore=num1 + num2; document.forms[5].score.value=newscore } function changeLocation(index){ force=parseFloat(location) + parseFloat(index); location=force; if (location==0){ document.forms[0].dialogbox.value=locDesc[0]; document.forms[5].itemhere.value="None"; } if (location==1){ document.forms[0].dialogbox.value=locDesc[1]; document.forms[5].itemhere.value="None"; } if (location==2){ document.forms[0].dialogbox.value=locDesc[2]; document.forms[5].itemhere.value="None"; } if (location==3){ document.forms[0].dialogbox.value=locDesc[3]; document.forms[5].itemhere.value="None"; } if (location==10){ document.forms[0].dialogbox.value=locDesc[4]; document.forms[5].itemhere.value="None"; } if (location==11){ document.forms[0].dialogbox.value=locDesc[5]; document.forms[5].itemhere.value="None"; } if (location==12){ document.forms[0].dialogbox.value=locDesc[6]; document.forms[5].itemhere.value="None"; } if (location==13){ document.forms[0].dialogbox.value=locDesc[7]; document.forms[5].itemhere.value="None"; } if (location==20){ document.forms[0].dialogbox.value=locDesc[8]; document.forms[5].itemhere.value="None"; } if (location==21){ document.forms[0].dialogbox.value=locDesc[9]; document.forms[5].itemhere.value="None"; } if (location==22){ document.forms[0].dialogbox.value=locDesc[10]; document.forms[5].itemhere.value="None"; } if (location==23){ document.forms[0].dialogbox.value=locDesc[11]; document.forms[5].itemhere.value="None"; } if (location==30){ document.forms[0].dialogbox.value=locDesc[12]; document.forms[5].itemhere.value="Key"; } if (location==31){ document.forms[0].dialogbox.value=locDesc[13]; document.forms[5].itemhere.value="None"; } if (location==32){ document.forms[0].dialogbox.value=locDesc[14]; document.forms[5].itemhere.value="None"; } if (location==33){ document.forms[0].dialogbox.value=locDesc[15]; document.forms[5].itemhere.value="None"; pit(); } if (location != 0 && location != 1 && location != 2 && location != 3 && location !=10 && location !=11 && location !=12 && location !=13 && location !=20 && location !=21 && location !=22 && location !=23 && location !=30 && location !=31 && location !=32 && location !=33 ) { alert ("You cant go there! The water blocks your way."); location=parseFloat(location) - parseFloat(index); } //alert(force + " and location" + location); } function takeItem(){ if (document.forms[5].itemhere.value != "None") { document.forms[5].your1.value=document.forms[5].itemhere.value; upscore(bonus); } else { alert("There's nothing here!") } } function useItem(itemtouse) { if (itemtouse == "Key" && location == 2) { document.forms[0].dialogbox.value="You Win! The Princess gives you a big Kiss, and Hillary reluctantly returns you to the land of Bat....\rYAY!" upscore(1000); } else { if (itemtouse == "Key" && location == 12) { document.forms[0].dialogbox.value="You picked the wrong Princess. The Witch cackles as she shoots a bolt of flame at your head. You Die!" document.forms[5].score.value=zero } else{ alert ("I cannot use that here"); }} } function pit() { document.forms[0].dialogbox.value= document.forms[0].dialogbox.value + "\rDid I forget to mention the Dragon? Oops. This huge monster thunders up and takes a big bite out of your face. You die." document.forms[5].score.value=zero } // end Functions // end The Engine --></script> <h1 align=center>Foobar the Bazbarian!</h1> <table border align=left><tr><td colspan=2><form><!-- form 0 --> <textarea rows="10" cols="50" name="dialogbox" wrap="virtual"> </textarea></form><tr><td><h4 align="center">Movement</h4> <table border ><tr><td></td><td><form><!-- form 1 --> <input type="button" Value="North" Name="GoNorth" onClick="changeLocation(-1)"> </form></td><td></td><tr><td><form><!-- form 2 --> <input type="button" Value="West" Name="GoWest" onClick="changeLocation(-10)"> </form></td><td align=center><B>GO</B></td><td><form><!-- form 3 --> <input type="button" Value="East" Name="GoEast" onClick="changeLocation(10)"> </form></td><tr><td><tr><td></td><td><form><!-- form 4 --> <input type="button" Value="South" Name="GoSouth" onClick="changeLocation(1)"> </form></td><td></td></table> <td valign=top><form><!-- form 5 -->Your Score: <input type="text" name="score"><br> Items Here: <input type="text" name="itemhere"><br> Your Items:<br> <input type="text" name="your1"><input type="button" Value="USE" Name="use1" onClick="useItem(document.forms[5].your1.value)"><br> <input type="text" name="your2"><input type="button" Value="USE" Name="use2" onClick="useItem(document.forms[5].your2.value)"><br> <input type="text" name="your3"><input type="button" Value="USE" Name="use3" onClick="useItem(document.forms[5].your3.value)"><br> <input type="text" name="your4"><input type="button" Value="USE" Name="use4" onClick="useItem(document.forms[5].your4.value)"><br> <input type="button" Value="TAKE ITEM" name="takeme" onClick="takeItem()"> <input type="button" Value="QUIT" name="quitme" onClick="history.go(- 1)"> <input type="button" Value="RESET" name="resetme" onClick="initgame()"> </form></table><p><font size="-1">Created and copyright Andrew Wooldridge</font><p> <hr align="50%"> You are FOOBAR, the Bazbarian from the land of Bat. You and the Princess of Zfoeps have been kidnapped by the Wicked Witch Hillary. As a challenge, Hillary has imprisoned herself and the Princess in two cages. You must search this small island to free the Princess! Search around and find the key to unlock her cage. If you let out the wrong girl you die! If you free the Princess you win! Click RESET to Start. <br clear=left> Email me if you find a bug. <a href="mailto:andreww@c2.org">andreww@c2.org</a> </BODY> </HTML>
This section covers the final pieces of information you need to complete your exploration of JavaScript and forms. The last two form-based objects, submit and reset, are accompanied with an example of a simple mail-in form that checks the input before it is sent back to you.
The submit Object The submit button was originally intended in HTML to be the final button a user would click to send a form back to the server. It would submit information, send feedback, or present a structured request for new information (you see this in search engines like Yahoo!). With JavaScript, you can now use this button to also send all of the information collected in a form to another window on your browser, or to the same window itself, which causes the contents of the window to change in some way. An example of this is changing the background color of the window based on the user's preference on a form. You create a submit object by using the following syntax:
<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.
The reset Object The reset button allows a user to completely reset a form's input fields to their defaults. You create a reset object in JavaScript by using the following syntax:
<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
<html> <script language=JavaScript> <!-- hide me function testone() { if (document.forms[0].elements[0].value==""){ alert("Please put a name in the first field!") } function testtwo (){ if (document.forms[0].elements[2].value.length <5){ alert("Please input at least 5 characters") } function testthree(){ if (document.forms[0].elements[4].value=="No"){ alert("Please change field three!") } // end hiding --> <form> <h1>Below is a series of fields that you must set before you can send this form</h1> <input type=text name=one value=""> Input your name (any text) <input type=button name=check value=checkme onClick="testone()"><p> <input type =text name=two >Input at least 5 characters <input type = button name=checktwo value=checkme onClick="testtwo()"><p> <input type = text name=three value="No">Change this to something else <input type=button name=three value=checkme onClick="testthree()"><p> </form> </html>
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.