If you have been reading this book through to this point, you have proven that you have more than just a casual interest in JScript (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 JScript scripts for your site. Most of the sites that you find today were built using many of the concepts in this chapter. Once you have the ability to use forms to lay out input and output areas; to create buttons to accept questions, replies, or other input; and to use "back-end" JScript 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 JScript, 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 by your Web site visitor.
JScript is one of the first scripting languages that applies an object-oriented approach (via its roots in Java) to writing and modifying Web pages. JScript 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 JScript Objects."
This chapter and the next take you through the objects in JScript 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 using HTML forms, buttons, and text boxes to allow a user to click buttons on a calculator and see the results immediately (see Figure 6.1). We will use the term applettes as an alternative to Java's applet-which is a small program that runs on your browser. JScript scripts are smaller, yet might perform many of the same tasks you see in Java. Thus, you could think of them as mini-applets.
Figure 6.1: A Web site using a calculator in JScript.
Before JScript, 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 often 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. All of these CGI operations were conducted on the server, so that all the information in the form had to be sent back to the server and manipulated.
Using JScript, you can place much of the work on the client side, which can reduce dramatically the connection times between the client (the browser) 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 to present an alert to the user if the information does not meet some specific requirements-such as number of characters or whether the field is empty.
Before we delve into the secrets of JScript 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> | Textarea Input Box size |
<TEXTAREA NAME="somename">...</TEXTAREA> | Textarea name |
<TEXTAREA WRAP=OFF> | Wraps the text |
This tag must begin and end your form.
The following are attributes of the <FORM> tag:
This tag creates various input fields. For example, the following HTML code:
<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:
This tag presents 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. You can then select one, or 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 fewer) and enable the user to scroll through the rest.
Figure 6.2: HTML supports various forms of input fields.
Figure 6.3: HTML source code of the input fields in Figure 6.2.
The following list gives 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 just under an 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. |
This tag designates a selectable item, and is used within the <SELECT> and </SELECT> tags. The following list describes the attributes an <OPTION> might have:
This tag provides 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:
Figure 6.4: Select fields may have several different sizes.
Figure 6.5: HTML source code for Figure 6.4.
This section introduces you to JScript'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 output.
You will learn about buttons, check boxes, and option buttons. These form elements consist of all the "clickable" elements. Mouse clicks on these elements can be used to trigger JScript 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 JScript has enhanced them with its ability to monitor their status (such as whether an option 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 JScript to bring new life to your forms. We will examine how JScript builds special objects as it reads your HTML code, and we'll explore how to use these objects to create an interactive form.
The form Object. Whenever you declare a <FORM>...</FORM> in your Web page, JScript 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 Attriubtes
<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:
JScript places each form it finds in a page into an array called forms. You can access each form either by 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].
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, see Listing 6.2.
Listing 6.2 Example of Accessing a Form Element in Jscript
<script language="jscript"> <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, to open a new URL, or perform any other action that JScript 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.6. Upon clicking the button, you will see an alert that looks like Figure 6.7.
Listing 6.3 Using a Button Form Element in JScript<HTML>
<HEAD> <TITLE>Button Example</TITLE> <script language="JScript"> <!-- hide me from other browsers function hey() { document.alert("Hey there! You pushed the button!") } // end hiding from other browsers --> </script> </HEAD> <BODY> <form> <h1>Click below for an alert!</h1> <input type="button" name="alertbutton" value="Click Me!" onClick="hey()"> </form> </BODY> </HTML>
Figure 6.6 : Web page with Alert button example.
Figure 6.7 : Here's the alert!.
You can access the properties of the button object in Listing 6.3 by using the following:
document.forms[0].elements[0].name
or:
alertbutton.name
If you wanted to retrieve the name of the button as a string object, you could use either of the following examples-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. Reloading the page alone does not implement the change, because 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 9 "Creating Your Own JScript Objects." |
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 or tick) inside it. Think of a check box as an On/Off switch.
A user can flip this switch on or off by clicking his or her mouse inside this box. Clicking here can also trigger an onClick event in your script. You create a check box 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 Figure 6.8).
Listing 6.5 Using the Checkbox Object
<html> <script language="jscript"> function mystatus(){ (document.theForm.theCheckbox.checked) ? alert("The box is checked") : alert("The box is not checked") } </script> <form name="theForm"> <input type="checkbox" name="theCheckbox" value="myValue" onClick="mystatus()"> </form> </html>
Figure 6.8 : A Web page with a check box.
When you click the check box so that it is checked, you will see something like what is shown in Figure 6.9. If you then "uncheck" it, you will see an Alert box like that shown in Figure 6.10.
Figure 6.9 : Once the check box is checked, you see this alert.
Figure 6.10: Clicking the check box 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 want 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 option buttons off except for the one that was picked. In other words, when you click one option 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 from accessing it from the checkbox object. Because all of the option buttons of a given group have the same NAME attribute, you access individual option buttons by adding an index value to the NAME. The format for doing this is as follows:
You can click a specific option button in JScript by using the following:
radioName[index1].click()
Listing 6.7 is an example of using option buttons with JScript. The result is shown in Figure 6.11.
Listing 6.7 Option 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>
Figure 6.11: A Web page example of using option buttons to constrain user input.
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 he or she just has to type it into the box. This is a quick way for you to offer both a series of preset choices, as well as allow a user to enter 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 JScript 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 or she last accessed your page, or some preference that he or she 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 Internet Explorer's "cookies" for compatability with 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.
Internet Explorer cookies are small strings of text; they are either stored in a single file named COOKIES.TXT or in separate files in a folder named COOKIES. 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);
Using hidden fields adds a sense of "state" to the Web. What this means is that usually a Web site has no real way of knowing whether visitors to that Web site had just been there moments ago, or whether they are 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 they receive-such as a timestamp-and retrieve that reminder whenever they submit 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 login screen and keep the password of that login 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 JScript, 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 shown as follows:
The password
object uses the focus,
blur,
and select
event handlers as methods. JScript imposes certain security restrictions
on the use of the password
object, however. It is not possible to check the validity of a
password before a user actually sends it back to the server for
a login. This restriction was introduced to prevent authors of
malicious script code from capturing passwords. For this reason,
you cannot get at the value
field of a password
object.
Note |
Don't confuse the password object with the hidden object. The password object conceals what a user types into 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 accommodate the additional text. In JScript, 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 "Built-In JScript Objects," you saw a script that used this field to display a constantly changing digital clock.
You create a JScript text object using the syntax in Listing 6.8.
Listing 6.8 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.
Table 6.2 Text Object Properties
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.
Table 6.3 Text Object Methods
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=textonChange="alert('changed')"> | Runs "alert()" if the text has changed when focus leaves this field |
onFocus | <input type=textonFocus="alert('start typing!')"> | Runsalert()"when user clicks in (or otherwise gives focus to) this field |
onSelect | <input type=textonSelect = "alert('text selected!')"> | Runs "alert()" once some text in this field is selected |
The script in Listing 6.9 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 Figure 6.12).
Listing 6.9 Event Handlers and Text Fields
<HTML> <HEAD> <TITLE>Text Field Example</TITLE> <script language = "jscript"> <!-- 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> </HEAD> <BODY> <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> </BODY> </HTML>
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. For example, this is the case if you are providing 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 JScript, use the syntax shown in Listing 6.10.
Listing 6.10 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 attributes, 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.
The textarea
input field is used in Andrew Wooldridge's game, 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 text area from one in which you require a user to input long
lines of text to displaying something like a miniature computer
terminal. Listing 6.11 shows this program's code, and Figure 6.13
provides a sample display of how it might look on a Web page.
Listing 6.11 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 beckons for you to unlock the cage.' locDesc[3]='The beach laps 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 at you. You hear screaming to the South.' locDesc[6]='In a clearing, you see a golden cage with a gorgeous 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 Mack 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:[email protected]">[email protected]</a> </BODY> </HTML>
This section covers the final pieces of information you need to complete your exploration of JScript and forms. The last two form-based objects, submit and reset, are accompanied by 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 JScript, 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"]>
Figure 6.13: Web page view of Foobar the Bazbarian.
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 JScript 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 does the submit object.
A Simple Form Validation Example. Listing 6.12 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.12 Form Input Validation Example
<html> <HEAD> <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 --> </SCRIPT> </HEAD> <BODY> <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> </BODY> </html>
From the example in Listing 6.12, 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.