Previous Contents Next
5. Basic Input and Output

We've started now to get some of the scripting details out of the way and you should be able to declare and manipulate variables and literals to perform some simple processing. However, you are particularly limited in not knowing how to input data into your scripts or to output results for the user to see. We've basically covered only what goes on internally to your scripts. But to be really useful, your scripts must be able to communicate with your users. Before proceeding with a discussion of additional script processing commands, let's take a short detour and consider some of the fundamental ways in which script input and output can be handled.

Using Forms

A reasonably effective way of performing input and output operations is through the use of form fields. You can use text fields as input areas into which users enter their data, and you can use them to display processing output.

Recall that forms are defined with HTML <FORM> and <INPUT> tags. For example, a simple form to provide two data input areas, an output area, a button to initiate processing, and a button to reset the form is defined with the following tags:


<FORM>
<INPUT TYPE=TEXT NAME="Input1" SIZE=10> Input1<BR>
<INPUT TYPE=TEXT NAME="Input2" SIZE=10> Input2<BR>
---------------------<BR>
<INPUT TYPE =TEXT NAME="Output" SIZE=10> Output
<BR>
<INPUT TYPE=BUTTON NAME="Run" VALUE=" Run ">
<INPUT TYPE=RESET NAME="Reset"><BR>
</FORM>

Input1
Input2
---------------------
Output



Of course, you can add to, rearrange, or dress up the form as you see fit. The point is you now have text areas that can be used for input and/or output, a run button to execute the script, plus a reset button to clear the fields. The user can click inside a field to enter data and use the tab key to move from field to field.

An Application

Let's say, for example, that you wish to create an application that calculates lap speeds at various race tracks. The user will enter the name of the track in the first field, the length of the track (in miles) in the second field, and the lap time (in seconds) in the third field. Your script will then calculate the miles per hour and display the result in the fourth field. You can use the model form described above, modified for your application. Note in the following code that the form has been included inside a table to provide borders and alignment.

<FORM>
<TABLE BORDER BGCOLOR=SILVER CELLPADDING=5>
<TH>Lap Speed Calculator</TH>
<TR>
    <TD>
    <INPUT TYPE=TEXT NAME="Track" SIZE=25> Enter Track<BR>
    <INPUT TYPE=TEXT NAME="Length" SIZE=10> Enter Track Length (miles)<BR>
    <INPUT TYPE=TEXT NAME="Time" SIZE=10> Enter Lap Time (seconds)<BR>
<TR>
    <TD>
    <INPUT TYPE =TEXT NAME="Speed" SIZE=10> Speed (mph)
    <INPUT TYPE=BUTTON NAME="Run" VALUE=" Run ">
    <INPUT TYPE=RESET NAME="Reset">
</TABLE>
</FORM>

Lap Speed Calculator
Enter Track
Enter Track Length (miles)
Enter Lap Time (seconds)
Speed (mph)


Once the form has been defined in HTML, you are ready to write the script to make the necessary calculations and display the results.

Script Access to Form Fields

In previous scripts we declared variables to create and hold the data values that were to be used in calculations. In the present case, however, data values already exist in the form fields when the user enters them. Therefore, all our script needs to do is get access to these existing values, make the required calculations, and place the result in a form field. No variables are needed as temporarily holding areas for the data. This is likely to be the case whenever processing data from forms.

In JavaScript you can refer directly to values contained in form fields. The general format of the reference is:

form.fieldname.value

That is, the reference is to the current "form," plus the field as named in the associated <INPUT> tag, plus the "value" appearing in that field. Therefore, in the example application, the contents of the four form fields are referenced by

form.Track.value
form.Length.value
form.Time.value
form.Speed.value

(These formats and others that follow are derived from JavaScript objects, properties, and methods, topics that will be discussed more fully later. For the present, you can use these formats as general models without really understanding why you are doing so.)

These references can be used in a script just as if they were variables or literals. You also need to know that data in form fields are always treated as strings. Therefore, you cannot directly perform calculations with them. However, JavaScript has a built-in function (another topic to be discussed later) named eval that converts a pattern of numerals appearing in a string into a number. So, you can apply the function to those references that will be involved in calculations to convert the field values to numbers:

eval (form.Length.value)
eval (form.Time.value)

Once this is done, we can put together the formula for calculating lap speeds. These are given by the general formula: mph = miles / (seconds / 3600). That is, seconds are converted into hours and then divided into miles. In terms of the form fields, the calculations are:

form.Speed.value = eval (form.Length.value) / (eval (form.Time.value) / 3600)

Scripts within Form Fields

Now we're ready to apply this expression to our application. Recall from earlier discussion that scripts can appear in two different places in a document: either stand-alone within <SCRIPT> tags for self-running scripts or as part of HTML tags to respond to user-initiated events. In the current application we want the user to initiate processing by clicking on the "Run" button. So, we can insert the script as part of this button's definition:

<INPUT TYPE=BUTTON NAME="Run" VALUE=" Run "
    onclick="form.Speed.value = eval (form.Length.value) / (eval (form.Time.value) / 3600)" >


Note that the formula is included within an onclick event handler to respond to the user clicking on the button. In this case there is the single JavaScript statement to perform the computation and assign the result to the field form.Speed.value.

You can click on the "View Application" button to the right to view the complete script and the application side by side.

You could also "out-source" the processing to an external function. Consider, for example, the following JavaScript function defined to handle the processing of our lap speed application.

<SCRIPT>
function CalculateSpeed (Miles, Seconds)
{
    var Speed = Miles / (Seconds / 3600)
    return Speed
}
</SCRIPT>

In the first line of the script the function is named and identified as CalculateSpeed and is coded to receive two values--identified here as Miles and Seconds. When these two values are received, the function uses them in the calculation of a variable named Speed. Then, the value of variable Speed is returned to the statement calling the function.

Since the calculation is being handled by the function, all the input form needs to do is pass the appropriate values to the function and put the returned result in the appropriate form field. Here again the responsibility falls to the "Run" button:

<INPUT TYPE=BUTTON NAME="Run" VALUE=" Run "
    onclick="form.Speed.value = CalculateSpeed (form.Length.value, form.Time.value)" >

The onclick event handler calls the function named CalculateSpeed, passing to it the two values in the form fields named Length and Time (referred to in JavaScript as form.Length.value and form.Time.value). When the function finishes its calculation, the returned value is assigned to the form field named Speed (referred to in JavaScript as form.Speed.value). The <INPUT> tag does no actual processing; it passes data from the form to the function and disposes of the returned value.


You can click on the "View Application" button to the right to view the complete script and the application side by side.

This discussion of scripting techniques related to forms and functions has been fairly cursory. The idea is not to provide full coverage of either here, but to get you started with basic input and output methods. We'll have occasion to return to these topics throughout the rest of the tutorial.

Alert Messages Revisited

One of the easiest ways of communicating with users is with Alert messages. These were used in the previous topic to display outputs from functions. We'll discuss them more formally here. Click on the following button for a reminder of what they are:
These messages are created with the JavaScript alert command. The general format of the statement is:

alert ("...message..." | variables | + )

indicating that you can display combinations of text strings and/or variables concatenated with the + operator. You should recognize from the fomat that this is a function--a "built-in" function through which JavaScript displays messages passed to it.

When typing literal strings, the entire message must be typed as one continuous line of text. There can be no carriage return characters like you might enter in your HTML editor to break lines. This doesn't mean, however, that you cannot break lines in the message--you just can't do it in your editor. You can use the special characters \n to insert a carriage return in the message. Or, as in the example Alert box, a pair of return characters \n\n can be used to force a paragraph break:

<FORM>
<INPUT TYPE=BUTTON VALUE="Alert Message"
onclick="alert('\nThis is an Alert box. \n\nIt can be used to provide short messages or computational results to users. Alert boxes can be displayed automatically with a free-standing script, or displayed as a result of a user action.')" >
</FORM>

If you don't want to type one continuous line, you can always assign shorter text strings to variables and then display the variables in the Alert box:

<SCRIPT>
var Msg1 = "\nHere is the first part of the message, "
var Msg2 = "and here is the second part of the message, "
var Msg3 = "and here is the third part of the message."
alert (Msg1 + Msg2 + Msg3)
<SCRIPT>

You can place the script for an Alert box anywhere in your HTML document. If the alert command is coded in a free-standing script and not associated with a button or other user-activated device (as it is above), then the message is displayed when the page is first loaded. You can place your script in the <HEAD> section or at the beginning of the <BODY> section, for example, to display welcome messages or other opening messages.

You can also tie the Alert message to a button or other event handler. The following script defines a set of variables containing messages to be displayed, and the <FORM> tag describes a button that, when clicked, displays the concatenated messages:


<SCRIPT>
function Alert ( )
{
    var Msg1 = "\nHere is the first part of the message, "
    var Msg2 = "and here is the second part of the message, "
    var Msg3 = "and here is the third part of the message."
    alert (Msg1 + Msg1 + Msg3)
}
<SCRIPT>

<FORM>
<INPUT TYPE=BUTTON VALUE="Alerts from Variables"
onclick="Alert ( )" >
</FORM>


Confirm Messages

Similar to Alert messages are Confirm messages. The difference is that a Confirm box gives the user a choice. The box displays "OK" and "Cancel" buttons. Your script, then, can take alternative courses of action depending on which of these two buttons the user clicks.

<SCRIPT>
function BGColor()
{
    if (confirm ("Are you sure you want a black background?") ) {
         document.bgColor="black" }
    else {
         document.bgColor="white" }
}
</SCRIPT>

<FORM>
<INPUT TYPE=BUTTON VALUE="Background Color"
onclick="BGColor()">
</FORM>


Since scripting of Confirm messages requires knowhow of program decision making, we'll wait until that topic is covered before describing these messages in detail.

Prompt Messages

A Prompt box displays a text input area where the user can send of string of characters to your script. Click the button to see one:

<SCRIPT>
function YouTyped ( )
{
     TextString = prompt ("Type your name below:", "")
     alert ("\nYou typed \"" + TextString + ".\"")
}
</SCRIPT>

<FORM>
<INPUT TYPE=BUTTON VALUE="Prompt Box"
onclick = "YouTyped ( )">
</FORM>


The prompt command has two parameters: first, the text string (enclosed in quotes) that represents the prompt message, and second, the text string (enclosed in quotes) that optionally appears in the box's input area. The example uses a null string ("") so that this area is blank. When the user types in the text area and clicks the "OK" button, the typed string is return to the script where it can be assigned to a variable or used in some other way.

Quotes within Quotes

Note the use of quotes in the onclick and alert commands in the following <INPUT> tag.

<INPUT TYPE=BUTTON VALUE="Alert Message"
onclick = "alert ('Here is the message.') " >

What you should notice is that the onclick handler, being coded as part of the <INPUT> tag, requires its statements to be enclosed in quotes; also, the alert statement has its literal message in quotes. Whenever quotes are embedded within quotes, you must take care to alternate between regular quotes (") and apostrophes (') to differentiate the nested quotations. This situation arises often when embedding script commands within HTML tags. It can usually be avoided by having the onclick handler call a function to display messages.

Secondary Windows

Another way in which your script can communicate with users is through secondary windows that overlay the primary browser window. You've seen the following one before:

Secondary windows are created with the open command. Its general format is:

open ("document.html","windowname","window parameters")

where

"document.html " The name of the HTML document that you want to display in the secondary window.
"windowname" A name you supply for the window. This name is used for reference from <FRAME> and <A> (anchor) tags, which usually is not a consideration for your use; however, the name is required so you can just make one up.
"window parameters" Characteristics of the window. If you leave these parameters out, you get a standard browser window; otherwise, you can include any of the following individual parameters, separated by commas:

toolbar - displays the browser's toolbar;

location - displays the browser's location, or URL, bar;

directories - displays the browser's Directory Buttons bar;

status - displays the browser's status bar;

menubar - displays the browser's menu bar;

scrollbars - displays the window's scroll bars (which will appear only if necessary);

resizable - permits the user to resize the window;

width= - sets the width of the window, in pixels;

height= - sets the height of the window, in pixels.

The set of parameters used must be enclosed, as a group, in quotes and not contain any embedded spaces ("resizable,width=250,height=300").

 

Normally, a secondary window is created in response to a user-initiated event, so the open command is likely to be part of an HTML tag. The following code was used to display the previous button that produces the secondary window of JavaScript reserved words (note the alternating quotes) :

<FORM>
<INPUT TYPE=BUTTON VALUE="Reserved Words"

onclick="open ('reserved.html', 'secondary', 'scrollbars,width=150,height=300')" >
</FORM>

Writing to Secondary Windows

You might have occasion to create a secondary window and at the same time to write a message to it (rather than displaying a preexisting HTML document). Take a look at the action of the following button:

As you can see, the button opens a new secondary window and displays a header, a short message, and a close button. The code for this button includes a script function to display the window plus a button that calls this function:


<SCRIPT>
function WriteMessage()
{
    Win1=open ("","secondary","scrollbars,width=350,height=200");
    Win1.document.open();
    Win1.document.write("<CENTER><H3>Window Messages</H3><HR></CENTER>");
    Win1.document.write("Here is a message written from a script to the secondary window.");
    Win1.document.write("The script also displays a close button.<P>");
    Win1.document.write
        ("<FORM><INPUT TYPE=BUTTON VALUE='Close' onclick='self.close()' ></FORM>");
    Win1.document.close()
}
</SCRIPT>

<FORM>
<INPUT TYPE=BUTTON VALUE="Write Secondary"
onclick="WriteMessage()">
</FORM>


Let's take this a piece at a time. The button, of course, is defined in <FORM> and <INPUT> tags. Embedded within the <INPUT> tag is the JavaScript onclick command to call the function that will display the window and message.

The first line in the script,

Win1=open ("","secondary","scrollbars,width=350,height=200")

uses the open statement to describe and open a new secondary window. This statement is similar to what we have used before with two differences. First, no existing HTML document is specified in the window name parameter. Instead a null specification is provided: ("") --two quotes back to back. You cannot simply leave out the window name parameter; you must provide either the name of an existing HTML document or a null (undefined) name.

Second, the window being created is given an internal JavaScript name (Win1) by assigning the open command to it. From this point on, any scripting reference to the window can be made through this name.

The Win1.document.open() command in the second line opens what is called a document stream. In the previous statement a window was opened; in this statement the document to appear in that window is opened. At this point it is a blank document; however, the subsequent Win1.document.write script commands write to the document stream and are displayed in the document window.

Win1.document.write("<CENTER><H3>Window Messages</H3><HR></CENTER>")

writes a heading to the newly created document. In parentheses and enclosed in quotes is the text string to be written. Note in particular that not only is text written, but HTML tags as well. These tags are written as part of the text string in order to format the text. The new window is, after all, an HTML document. The statements,

Win1.document.write("Here is a message written from a script to the secondary window.") Win1.document.write("The script also displays a close button.<P>")

write the body of the text message, while

Win1.document.write
    ("<FORM><INPUT TYPE=BUTTON VALUE='Close' onclick='self.close()' ></FORM>")

writes the HTML tags necessary to display the close button. Notice here that the JavaScript code to close the window is included as part of the <INPUT> tag. The user can close a secondary window by clicking on the X button at the top-right of the window. An alternative is to provide a close button. The self.close( ) specification is JavaScript's way of getting a window to close itself.

Finally, the statement,

Win1.document.close()

closes the document stream, indicating the end of the writing activities to the document.

In this example we have written literal strings--enclosed in quotes. You can also define string variables and write these; for example:


<SCRIPT>
function WriteVariables ( )
{
    Var1 = "Here is the first variable"
    Var2 = "and here is the second variable"
    Var3 = "and finally the third variable."

    Win1=open ("","secondary","scrollbars,width=350,height=200")
    Win1.document.open()
    Win1.document.write ("<P>" + Var1 + " " + Var2 + " " + Var3 + "<P>")
    Win1.document.close()
}
</SCRIPT>

<FORM>
<INPUT TYPE=BUTTON VALUE="Write Variables"
onclick="WriteVariables ( )" >
</FORM>


Or, you can even write pictures:

<FORM>
<INPUT TYPE=BUTTON VALUE="Display Picture"
onclick="
Win1=open ('','secondary','scrollbars,width=350,height=200');
Win1.document.write ('<P>Here is a picture...<P><IMG SRC=imagefile.gif><P'>);
Win1.document.close( )"
>
</FORM>


When displaying pictures you may need to provide the full URL address (http://...etc...), especially when working under Internet Explorer 3.0.

Window Focus (Navigator 3.0)

After a message is displayed in a secondary window and then a script writes another message without the user having closed the first window, the message is written; however, the window is minimized on the task bar and you have to click it open from there. Netscape Navigator 3.0, though, has a JavaScript command to bring the window to the front of the screen even if the user has not closed the first window. The statement,

windowname.focus( )

can be placed in a script to bring "focus" to a window, causing it to be displayed, not minimized on the task bar. The windowname is the name of the window as assigned in the accompanying open statement (we've been using the name "Win1").

We have skimmed over the syntax of the JavaScript commands to handle input and output, and have not really explained much about their formats or parameters. All this will come in due course. Right now, we are simply providing general models that you can follow to begin writing your own user messages. We will fill in some of the gaps as we proceed. In the next topic we return to script processing and take a look at two of the most useful and powerful scripting techniques: decision making and looping.


Previous Contents Next