Chapter 3 Forms: Reading and Manipulating Buttons and Text

Javascript Guide

by Stephen Wilson (c) 1996

Note: These draft javascript tutorials are presented for the personal use of students in the Conceptual Design Department at San Francisco State University and for members of the Internet community. It is not permitted to creproduce sell, or redistribute without permission of Stephen Wilson. swilson@sfsu.edu

What Can Javascript Do to Simply the Web's Use of Forms

Contemporary Web pages often include interactive forms based on the well developed HTML standard supported by most browsers. Viewers indicate their desires by clicking on buttons and checkboxes, selecting options out of text selection fileds, and typing text into text input boxes. Examples include search engines, games, user informatiion sheets, educational applications, and the like. Typically forms are used in conjunction with CGI server scripts to customize responses for the Web user. Figure 3.1 show the process which includes the following steps:

The combination of forms and server scripts have greatly increased the responsiveness of the Web. Unfortunately the need to send the responses back over the Internet to a server and wait while the script processes the information can be time consuming and can overload servers with processing demands. Javascript is seen as a way to greatly simplify the steps in responding to forms.

You can embed scripts along with the Web page containing the form. The user will be able to indicate choices in the form and then get an almost instantaneous response. Because the script is locally present there is no need to send the information over the Internet and wait for a server that may be required to respond to hundreds of similar simultaneous requests. Enthusiasts believe this responsiveness may revolutionize the Web and eliminate the need for perhaps 60% of current form's reliance on servers.

Of course, local scripts will not be able to substitute for all current systems. For example, those that rely on rapidly changing time-based information cannot easily be embedded in local scripts (&& example). Similarly, those systems that rely on huge databases and/or sophisticated computing such as the full search engines like Lycos or Yahoo cannot be instituted locally. With the advent of local scripting your responsibility as a Web author will include determination of what functions can be locally scripted.

What is the Form Object, Its Elements, and its Properties?

>A form object in Javascript is closely related to regular HTML created forms. It is established by using the same <FORM>...</FORM> tags and can encompass standard attributes such as METHOD and ACTION. Also it can have the same kinds of elements that regular forms have such as buttons and text input fields.

In Javascript there are some slight modifications. The attributes are considered properties and indicated with the dot format. Also two new properties are added. Here are the attributes of the form object.

Note also that the form is itself considered a subelement of the document and can be indicated by the dot notation. The following example refers to a form that was given the name "basicinfo".

document.form.basicinfo&&

This allows your scripts to refer to specific forms when there are more than one. You can also indicate the forms by the order they appear on a Web page. For example, if there were two forms the first one would be document.form[0] and the second would be document.form[1]

All the various types of input objects from standard HTML markup are also addressable by Javascript. They are considered sub elements of the form object. All the following form elements are included: button, checkbox, password, radio, reset, select, submit, text, and textarea. Just to remind you HTML form format tags Figure 3.2 shows a Web page with two simple forms along with the HTML code that would create those forms.&&

(&&insert fig 3.2 2 forms)

Each form element has its own properties. These include the standard HTML attributes TYPE, NAME, and VALUE as well as characteristic unique to each type of input elment. The examples below show the code fragments to create a button, checkbox, and text imput area. Remember it would need to be embedded within a regular HTML form structure.

<FORM ACTION="http://netadd.com/respond.cgi" METHOD="Post" NAME="basicinfo"> <INPUT TYPE="button" NAME="sex" VALUE="Male"><P> <INPUT TYPE="checkbox" NAME="age" VALUE="young" CHECKED> Under 18<P> <INPUT TYPE="text" NAME="personaname" VALUE="" SIZE=25> Type your name<P> </FORM>

These elements would appear on the Web page as part of a form. When clicked each would assign the value selected or typed to the name of the element; these name/value pairs (for example age="young") would be sent to the server along with other information pairs when the form was submitted. Those of you not familiar with HTML FORM tags should refer to my book, World Wide Web Design Guide , or any other source that explains the use of Web forms. You will need to be knowledgeable about these tags and structures in order to use Javascript to manipulate thse elements.

Your Javascript code could refer to these elements by their names. For example the text field in the examples above would be document.basicinfo.pername. If there were more than one form, you would have to identify which form included the text field. In this example the text field pername is part of the form named basicinfo.

How to Use Text Fields for Communicating with Users

Typically forms are employed in order to give users the opportunity to communicate with the server. This book will present many examples of scripts checking the information and creating appropriate responses. Javascript allows you to communicate in the other direction. Your scripts are not restricted to just reading the information that the user has input. You can set the values of text fields as a way of presenting text to the user. You can even create animated displays.

This presentation of the text is accomplished by using the object notation to identify specific text fields and then assigning values to them. The text then appears in the box. Checkboxes and radio buttons can be similarly toggled under script control. The next section shows an example of an animated text display.

Sample Script to Animate Text in Text Field

s

This script will set up a form that asks for user input. It will animate text in boxes that surround it to urge the user to provide the information. To accomplish this, we must first use standard HTML form tags to create the input fields for user typing. We must also create text fields that we will use to create the animation. Figure 3.3 shows the basic form that was created by the following HTML structures.

For the sake of illustrating methods of using Javascript to refer to different forms that appear on a page, the examples presents the information in 3 forms. It could have also been combined into one form. It places the fields for user input in the middle form called f2 and the fields that will animated text placed into them into fields f1 on top and f3 on the bottom. Also it places the input elements in form f1 and f3 into tables in order to gain more control over their placement. f1,f2, and f3 are just arbitrary names given to the fields. In this example "Answer Soon" text appears and disappears, moving around the fields from left to right on the top and then from left to right on the bottom.

<HTML> <HEAD> <TITLE> Animated Text</TITLE> </HEAD> <BODY > <FORM NAME="f1"> <TABLE> <TR> <TD> <INPUT NAME="ta1" TYPE="text" SIZE="20"> <TD> <INPUT NAME="ta2" TYPE="text" SIZE="20"> <TD> <INPUT NAME="ta3" TYPE="text" SIZE="20"> </TABLE></FORM> <HR> <FORM NAME="f2" ACTION="http://netadd.com/nam.cgi" METHOD="POST"> <CENTER> Name <INPUT NAME="pername" TYPE="text" SIZE="20"> Name<P> Age <INPUT NAME="perage" TYPE="text" SIZE="5"> Age<P> Occupation <INPUT NAME="perocc" TYPE="text" SIZE="20">Occupation <P> <INPUT TYPE="Submit" VALUE="Submit"> <INPUT TYPE="Reset" VALUE="Reset"> </CENTER> </FORM> <HR> <FORM NAME="f3"> <TABLE> <TR> <TD> <INPUT NAME="ta4" TYPE="text" SIZE="20"> <TD> <INPUT NAME="ta5" TYPE="text" SIZE="20"> <TD> <INPUT NAME="ta6" TYPE="text" SIZE="20"> </TABLE></FORM> <SCRIPT LANGUAGE= "javascript"> setTimeout("document.f1.ta1.value = 'Answer Soon'", 1000) setTimeout("document.f1.ta1.value = ''", 1300) setTimeout("document.f1.ta2.value = 'Answer Soon'", 1600) setTimeout("document.f1.ta2.value = ''", 1900) setTimeout("document.f1.ta3.value = 'Answer Soon'", 2200) setTimeout("document.f1.ta3.value = ''", 2500) setTimeout("document.f3.ta4.value = 'Answer Soon'", 2800) setTimeout("document.f3.ta4.value = ''", 3100) setTimeout("document.f3.ta5.value = 'Answer Soon'", 3400) setTimeout("document.f3.ta5.value = ''", 3700) setTimeout("document.f3.ta6.value = 'Answer Soon'", 4000) setTimeout("document.f3.ta6.value = ''", 4300) </SCRIPT>

All the code to establish fields and tables should be famiilar to readers with HTML experience. The new part is the code enclosed in the <SCRIPT> tags. The heart of these commands are expressions that assign values to particular fields. For example the code line document.f1.ta1.value = 'Answer Soon' tells the browser to find the document object (the Web page) and then the form that is a subelement of it called f1 (the first one on top) and then the subelement of that form called ta.1 (the first text entry field). Once that element is targeted, the script tells the browser to change the value property of that text field by assigning it the text "Answer Soon". The Value attribute in standard HTML markup is the text that a field contains (usually because a user has typed it there.). Javascript has extended this allow the script to type values. To the user the text appears as in an animation. After text appears the sample script makes it disappear by assinging the blank value "" to the same text field.

The script could not just list all these commands because the browser would instantaneously apply all the values and the user would not see any animation. To time the actions, the script uses the same setTimeout method described in earlier example 2.3?? &&. Remember this method requires two parameters - first the expression to be acted on and then following a comma, the number of milliseconds to wait before acting on the first experession. So you can see that the code that assigns values is the first expression in each of these setTimeout lines. For example, the first line is setTimeout("document.f1.ta1.value = 'Answer Soon'", 1000). In this line setTimeout tells the browser to wait 1000 milliseconds before making the text appear. The next line makes the text dissappear at 1300 milliseconds. Thus, three tenths of a second after the text appears, it dissappears.

The syntax of the setTimeout method requires that its parameters be enclosed in parentheses and separated by a comma. The first experession to be acted upon must be placed in quotes. This complicates matters because in Javascript commands that assign properties to have certain values (value="this text") required the text being assigned to also be in quotes. Thus Javascript could get confused. It uses the convention of using single quotes when they are inside of quotes. As a result 'Answer Soon' must be enclosed in single quotes.

For the sake of clarity, this example has shown how to assign the values to text fields in the most simple way possible. Like most languages Javascript offers more elegant ways to acoomplish this action through the use of functions, arrays, and loops. Later chapters will show how to write this script with many fewer lines.

Aesthetics of Animated Display

s

This example has shown a modest animation of appearing/disappearing text moving from left to right on the top and the bottom. Javascript will give your amazing capabilities to create animated displays of all kinds. Realize, however, with this capability comes a design challenge. How can you create animations which integrate closely with the goals of your Web pages?

Those without a lot of multimedia design experience tend to overuse these kinds of features when they discover them. Everything starts flashing and moving. Unfortunately overuse can saturate the user and devalue your pages in the minds of visitors You will want to use these capabilities sparingly and usually in the service of some goal. For example, I would be warn against using this "Answer Soon" display every time you ask the user for input. If your page, however, is set up to automatically update and the user has not typed anything after a period of time, the animated display might make sense. The later chapter on use of Date and Time (&&) will show you how to write this kind of script. You will no doubt discover all kinds of situations where animated displays enhance your communication.

Also, realize that even with this simple example, we could have modified its function in ways that would have created very different experiences for the visitor. Figure 3.5 (&& ) shows many different ways the text could have been moved through the text fields.

(Insert fig 3.5 variations on animated fields)&&

<HTML> <HEAD> <TITLE> Animated Text</TITLE> </HEAD> <BODY > <FORM NAME="f1"> <TABLE> <TR> <TD> <INPUT NAME="ta1" TYPE="text" SIZE="20"> <TD> <INPUT NAME="ta2" TYPE="text" SIZE="20"> <TD> <INPUT NAME="ta3" TYPE="text" SIZE="20"> </TABLE></FORM> <HR> <FORM NAME="f2" ACTION="http://netadd.com/nam.cgi" METHOD="POST"> <CENTER> Name <INPUT NAME="pername" TYPE="text" SIZE="20"> Name<P> Age <INPUT NAME="perage" TYPE="text" SIZE="5"> Age<P> Occupation <INPUT NAME="perocc" TYPE="text" SIZE="20">Occupation <P> <INPUT TYPE="Submit" VALUE="Submit"> <INPUT TYPE="Reset" VALUE="Reset"> </CENTER> </FORM> <HR> <FORM NAME="f3"> <TABLE> <TR> <TD> <INPUT NAME="ta4" TYPE="text" SIZE="20"> <TD> <INPUT NAME="ta5" TYPE="text" SIZE="20"> <TD> <INPUT NAME="ta6" TYPE="text" SIZE="20"> </TABLE></FORM> <SCRIPT LANGUAGE= "javascript"> setTimeout("document.f1.ta1.value = 'Answer Soon'", 1000) setTimeout("document.f1.ta1.value = ''", 1300) setTimeout("document.f1.ta2.value = 'Answer Soon'", 1600) setTimeout("document.f1.ta2.value = ''", 1900) setTimeout("document.f1.ta3.value = 'Answer Soon'", 2200) setTimeout("document.f1.ta3.value = ''", 2500) setTimeout("document.f3.ta4.value = 'Answer Soon'", 2800) setTimeout("document.f3.ta4.value = ''", 3100) setTimeout("document.f3.ta5.value = 'Answer Soon'", 3400) setTimeout("document.f3.ta5.value = ''", 3700) setTimeout("document.f3.ta6.value = 'Answer Soon'", 4000) setTimeout("document.f3.ta6.value = ''", 4300) </SCRIPT> </BODY> </HTML> Section A shows the samples scheme of each field one at a time. B shows all of the fields coming on and all going off at the same time. C shows all the top coming on at the same time, going off after a delay, and all the bottom coming on. D shows top and bottom moving in different directions. E shows top and bottom pairs coming on and off in sequence across the page. F shows random on and offs.

Also realize that the sample uses even time delays between ons, offs and the next display. You could compose the text appearance in different rhythms. For example keeping text on longer than off creates a different feel than keeping text off longer than on. The time delays are easily adjusted merely by changing the time parameter in each setTimeout line.

Sample Script to Animate Radio Buttons

This example shows how you could use similar Javascript commands to animate a display of radio buttons. Remember radio buttons are the HTML form element that toggles highlight when users click on them. Javascript allows a script to control the appearance, giving you another animated display possibility. In this example the top line of buttons animates from left to right while the bottom animates from right to left.

<HTML> <HEAD><TITLE> Animated Buttons</TITLE></HEAD> <BODY > <HR> <CENTER> <FORM NAME="bb"> <TABLE> <TR> <TD> <INPUT NAME="bu" TYPE="radio" > <TD> <INPUT NAME="bu" TYPE="radio" > <TD> <INPUT NAME="bu" TYPE="radio" > <TD> <INPUT NAME="bu" TYPE="radio" > <TD> <INPUT NAME="bu" TYPE="radio" > <TD> <INPUT NAME="bu" TYPE="radio" > <TD> <INPUT NAME="bu" TYPE="radio" > <TR > <TH COLSPAN=7> <input NAME="re" TYPE="reset" value="Welcome to this age"> <TR> <TD> <INPUT NAME="bu2" TYPE="radio" > <TD> <INPUT NAME="bu2" TYPE="radio" > <TD> <INPUT NAME="bu2" TYPE="radio" > <TD> <INPUT NAME="bu2" TYPE="radio" > <TD> <INPUT NAME="bu2" TYPE="radio" > <TD> <INPUT NAME="bu2" TYPE="radio" > <TD> <INPUT NAME="bu2" TYPE="radio" > </TABLE></FORM></CENTER> <HR> <SCRIPT LANGUAGE= "javascript"> setTimeout("document.bb.bu[0].checked = true", 1000) setTimeout("document.bb.bu2[6].checked = true", 1000) setTimeout("document.bb.re.click()", 1300) setTimeout("document.bb.bu[1].checked = true", 1300) setTimeout("document.bb.bu2[5].checked = true", 1300) setTimeout("document.bb.re.click()", 1600) setTimeout("document.bb.bu[2].checked = true", 1600) setTimeout("document.bb.bu2[4].checked = true", 1600) setTimeout("document.bb.re.click()", 1900) setTimeout("document.bb.bu[3].checked = true", 1900) setTimeout("document.bb.bu2[3].checked = true", 1900) setTimeout("document.bb.re.click()", 2200) setTimeout("document.bb.bu[4].checked = true", 2200) setTimeout("document.bb.bu2[2].checked = true", 2200) setTimeout("document.bb.re.click()", 2500) setTimeout("document.bb.bu[5].checked = true", 2500) setTimeout("document.bb.bu2[1].checked = true", 2500) setTimeout("document.bb.re.click()", 2800) setTimeout("document.bb.bu[6].checked = true", 2800) setTimeout("document.bb.bu2[0].checked = true", 2800) setTimeout("document.bb.re.click()", 3100) </SCRIPT> </BODY></HTML>

The core command in this example sets the various buttons checked property to true. When checked is true, a button is filled with black.

document.bb.bu[0].checked = true

Two sets of radio buttons are created; the top is arbitraily named "bu" and the bottom is arbitraily named "bu2". The dot notation is used to identify which button is being addressed. For example, the top left button is a member of the family of buttons with the name "bu" and that family of buttons are part of the form called "bb". Thus, part of its identification is document.bb.bu.

But there is a complication with radio buttons. Typically, radio buttons are created in families. Every radio button in the top family is given the same name - "bu" . In standard HTML that is the way you create toggle buttons. There must be some way to distinguish each toggle button. Javascript uses the convention of giving each member of the family an index in an array. It indicates arrays using brackets and starts arrays at 0, not 1. The first button in the top family is bu[0]; the next is bu[1].

To accomplish its effect of moving the black dot, the script moves through the radio buttons setting button's checked value to true. It then moves to the next one in the series (the next one to the right on the top and the next one to the left on the bottom.) To create an animation with the previous button becoming unfilled, something must be done to unfill them. The script could have added lines before the next fills to set the checked value to false. Thus the first part of the script could have looked like this:

setTimeout("document.bb.bu[0].checked = true", 1000)

setTimeout("document.bb.bu2[6].checked = true", 1000)

setTimeout("document.bb.bu[0].checked = false", 1300)

setTimeout("document.bb.bu2[6].checked = false", 1300)

setTimeout("document.bb.bu[1].checked = true", 1300)

setTimeout("document.bb.bu2[5].checked = true", 1300)

To illustrate another approach, the script illustrates use of click() method. The basic HTML code creates a reset button in the middle of the animated buttons which is given the value "Welcome to this Page" and the name "re". Remember reset buttons on forms turn off all checks. The click method simulates someone clicking on a button. This script calls the click method to simulates a click on the reset button to clean out the last buttons each time before new buttons are filled. In this example the reset button is identified by dot object notation as the button named "re" in the form named "bb".

document.bb.re.click()"

Methods are actions than can be applied to objects. Javascript's authors have stipulated that each object has certain methods it can respond to. Methods will be described more in chapter &&. Methods are indicated with dot notation in a way similar to elements and properties. The method is appended at the end of a object and requires parentheses. All button objects can respond to the click() method. This script tells the reset button to simulated being clicked as a way to erase buttons.

How Can You Respond to User Selections and Typing

The most common use of Web forms is solicitation of information from the user. The user is asked to click buttons, fill in text fields or choose text from select fields. The data is then sent to a server which customizes its responses based on these choices. Javascript gives you an easy way to embed this intelligence of response right into the Web page itself so nothing must be sent to the server.

You can write your scripts to ascertain what the user has done and respond accordingly. The method of identifying the values of particular buttons and fields is the same as used in previous examples in this chapter. For example you have used HTML to create a Web page with a form that asks for the user's name and address as in the example below.

<FORM NAME="basic"> Please Type Your Name<INPUT Name="persname" TYPE="text" SIZE="40"><P> Please Type Your Telephone#<INPUT Name="perstel" TYPE="text" SIZE="12"><P> </FORM>

This would create a simple input form. In HTML forms the material present in any text field is its VALUE attribute. In Javascript it is called its value property. Any subsequent script could thus refer to the information the user had typed in the fields by using dot notation to indicate the form and particular field of interest. The text in the name field (which is an element of the form called "basic") would be document.basic.persname.value and the text in the telephone field would be document.basic.perstel.value.

<h2>Sample Script to Customize Links Based on User Button Choices

This sample script demonstrates how to create a script that lets a user chose a category of infomation after which it dynamically generates an html page containing links relevant to that interest. It uses a simple form with radio buttons to determine interest. Just to add interest it also asks the users to type their name. Once the users are done chosing, they click on the submit button and the script generates the html document using their name. For the sake of clarity this example is very short with only one choice requested. The same principles, however, could be applied to more sophisticated sets of choices.

There are three major parts to this Web page and script: A. Javascript script cotaining the database of links for each kind of music, the function to create a unique page based on their choice, and the function to create a new Netscape window to show the page. B. HTML code to create the information request page cotaining an input form. C. Javascript code to set up default values.

This example briefly introduces functions, arrays, and window opening methods because they make the script more efficient. The script could be made event more compact by using more advanced techniques taught in later chapters.

(&&Insert fig 2.7 picture)

<HTML> <HEAD><TITLE>Choice</TITLE> <SCRIPT Language="javascript"> // sets up database of links - SECTION A1 muresources="" muresources["classical"]= "<A HREF='http://net.com/classical.file1'>Meditative classical music<A><P> <A HREF='http://net.com/classical.file2'>Provoking classical music<A>" muresources["rock"] = "<A HREF='http://net.com/rock.file1'>Popular rock music<A><P> <A HREF='http://net.com/rock.file2'>Exciting rock music<A>" muresources["ethnic"] = "<A HREF='http://net.com/mexican.file1'>Mexican music<A><P> <A HREF='http://net.com/Indian.file2'>Indian music<A>" function getLink() { // constructs unique page using name and choice of music - SECTION A.2 temp = muresources[choice] temp2 = "<TITLE>Custom Links</TITLE><H3>" +document.m.pername.value+", here are some links for you</H3><P>"+temp } function writeIt(){ // creates new window to display page - SECTION A.3 diswin = window.open(); diswin.document.open(); diswin.document.write(temp2); diswin.document.close() } function doAll(){ // master routine calls other functions - SECTION A.4 getLink(); writeIt() } </SCRIPT> </HEAD> <BODY > <!-- Sets up basic input form SECTION B --> <H3> Choose the kind of music you prefer<BR> and this page will fetch links of interest to you</H3> <HR> <FORM NAME="m" > Choose a kind of music<P> <INPUT TYPE="radio" NAME="mus" VALUE="classical" OnClick="choice='classical'" >Classical <BR> <INPUT TYPE="radio" NAME="mus" VALUE="rock" OnClick="choice='rock'">Rock<BR> <INPUT TYPE="radio" NAME="mus" VALUE="ethnic" OnClick="choice='ethnic'">Ethnic<BR> <HR> Please type your name<P> <INPUT TYPE="text" NAME="pername" SIZE=25> <HR> <INPUT TYPE="button" NAME="sub" VALUE="Show me links" OnClick=doAll()> <INPUT TYPE="reset" NAME="res" > </FORM> <SCRIPT> // sets defaults - SECTION C choice = "classical" document.m.mus[0].checked = true document.m.mus[1].checked = false document.m.mus[2].checked = false </SCRIPT> </BODY> </HTML>

The first section of the script (A.1) loads the database of links. Note that the text is prepared in standard HTML notation with relevant tags. The whole set of links and related anchor text is enclosed in quotes; any internal quotes need to use single quotes. Separating it into this database makes it easy to update this section. The script creates an array to store the different databases for classical, rock, and ethnic music links. It gives it the name "muresources".

An array is just a family of related values stored in a systematic way. More information about arrays is available in chapter &&. Each member is indicated by an index marker placed inside of brackets. The index can be numbers or text. The numbers start at 0. This example creates an array with 3 members. Each member can be read or changed by using this index notation. The example below shows the equivalent notation.

muresources[0] muresources["classical"]' classical music links text

muresources[1] muresources["rock"]' rock music links text

muresources[2] muresources["ethnic"]' ethnic music link text

The text names are used in the index because that allows us to use the variable choice (assigned values by the radio buttons) to automatically function to select the right member of the array. If the user selects rock music, "rock" is put into the variable choice and muresources[choice] will be equivalent to muresources[''rock"]. The variable muresources is initialized with the default value "".

Section A.2 of the script creates a Javascript function called getLink(). A function is a structure Javascript uses to create subroutines. You can think of it as a mini-program that can be called from other parts of the scirpt. Functions offer many adavantages. They allow you to modularize your script so different actions are separate and can be debugged more easily. They also allow reusable code; if they are written in a flexible generalized way they can be called repeatedly with different parameters. Chapter && will discuss functions in more detail.

Javascript expects functions in the following syntax - the word function, followed by the name you give the function, followed by parentheses, followed by opening brackets to enclosed the commands, followed by commands, ended by closing brackets.

function nameofunction(){

command 1

command 2....

}

This sample script names the first function getLink(). The middle letter does not need to be capitalized although many scriptors do use that convention. The parentheses must be there to indicate it is a function. Here they are empty; as you will see later, you may want to enclose parameters in the parentheses that the function will use in other functions you write. This fucntion constructs the Web page to be displayed. It creates a variable called temp to store the appropriate Web page text from the database. It retrieves this text by using the array notation discussed previously to identify which member of the variable muresources[] it needs. The variable choice has received its value from the radio button set in the form; that is if a user clicks "rock" the script for that button assigns the value "rock" to the variable choice. Thus,, the variable temp will be set equal to muresources["rock"]. The database section of the script has arranged for that variable to contain all the link text relevant to rock music.

The next part of the function constructs the rest of the Web page. It creates a variable called temp2 that will accumulate the pieces. First it places the TITLE tags and the title name "Customized Links". Next it creates a greeting line that includes the name of the user. It gets the user's name by reading the value of the text field where the user was supposed to type a name. That field is named pername and is part of a form named m. Thus, using dot notation the value of that field is document.m.pername.value. It completes the greeting sentence by adding text ", here are some links for you". Finally, it appends the variable temp which includes all the HTML link text. In Javascirpt text strings are concatenated using the "+" symbol.

The next section (A.3) creates a function called writeIt(). The script needs some place to display the document it has generated. Javascript has trouble changing a page that has already loaded so it needs to create a new window. Java script makes this easy by allowing you to apply the open() method to a window object. The syntax for opening a window requires you to assign a name for the new window: newname = window.open(). All subsequent references to that window need to use that name. The example uses the name "diswin". After opening the window it then opens a new document by using the open() method to a document: diswin.document.open(). This creates a place for all subsequent generated text to be sent. It next uses the write() method to send out the variable temp2 that contains the page that responds to the users choices: diswin.document.write(temp2). Finally, it must close the document which is a signal to Javascript to display the text: diswin.document.close(). Chapter && explains more details about using windows and documents.

There are design decisions to be made. This script leaves the window open rather than automatically closing the previous window when the user makes another request. This can clutter the monitor display, but it allows the user to keep several open at once. Also, text to be displayed does not have to appear in a totally separate window. If there were no active links involved we could have displayed text in a textarea in a form or in an alert box. The desire for active links requires the text to appear in a Netscape window or frame. Frames are discussed more in chapter &&.

The next function (A.4) creates one more function called doAll(), This function's purpose is to call all the other functions in the right order. This is the function that the button clicked by the user activates. It orchestrates the whole response event.

All of these functions are loaded in the HEAD section of the document because it is important they get loaded first. If the user clicked on a button that called a function that hadn't yet loaded (say because it was at the bottom of the page) an error alert box would confront the user.

The next major section of the page (B) creates the Web page that displays to the user. Most this uses standard HTML form tags. It has the following sections: greeting text, radio buttons to select the kind of music, a field requesting the user's name, and the button to see the links or reset the form. Users indicate their desire by clicking on one member of a radio button family named "mus". The fact that they are all members of the same family means they act as toggles; only one can be selected at a time.

The script adds one important new feature to each of these buttons. It places an onClick handler that activates whenever the button is clicked. Each handler sets the choice variable equal to the appropriate type of music for that button: onClick("choice='rock'") for the rock option. Note the onClick hander requires the action to be enclosed in parentheses and quotes and for single quotes to be used for inside quotes if required.

The Web page defines a text input field called "pername" that requests users to type their names. Finally the last section offers two buttons - a standard HTML reset button to reset the form and another regular button that shows the text "Show me links". This is the button that mobilizes the scripts into action to fetch the relevant links and display them in a new window. It accomplishes this by including a onClick handler. The action initiated is a call to the doAll function described earlier that calls the getLinks() and writeIt() functions.

Finally, the page finishes with another Javascript script (section C) to set a default value. Choice is given the value "classical" and the radio buttons are set with classical selected. The radio buttons are checked and unchecked by setting their checked property. False turns a button off (for example, the ethnic button) : document.m.mus[2] .checked= false.. This button is in the form named "m" in the family of buttons named "mus". Since three buttons are all share the name "mus" the array notation brackets must be used to indicate which button is the target. Choice must be given a value because an error would result if the user clicked on the "show me links" button before clicking on any of the radio choice buttons. Javascript would confront the user with an alert box saying choice is undefined.

This kind of Javascript can be quite useful. With small databases there is no reason to invoke the complication of a server script. This kind of script can quite adequately respond to user's interests.

&&Summary

- This page created by Stephen Wilson, Professor Conceptual Design, SFSU (http://userwww.sfsu.edu/~swilson) swilson@sfsu.edu
- More information about the Conceptual Design program is available at (http://userwww.sfsu.edu/~infoarts)
- It is a resource used in Art511 Art&Telecommunications course (http://userwww.sfsu.edu/~infoarts/Tele/Tele95.index.html)
- A comprehensive guide to Web design is available in the book World Wide Web Design Guide (Hayden Books) by Stephen Wilson
- The url of this page is (http://userwww.sfsu.edu/~infoarts/Tele/wilson.javascript3r.html)