Top Banner
Forms Tutorial Let's look at a very simple form: this code produces this <FORM ACTION="/cgi-bin/mycgi.pl"> favorite color: <INPUT NAME="color"> </FORM> favorite color: rea This form has all the required elements for a form: <FORM ACTION="/cgi-bin/mycgi.pl"> Start the form here. The ACTION attribute, which is required with every <FORM ...> tag, is used with CGI, discussed below . <INPUT NAME="color"> Data entry field. <INPUT ...> creates most types of form fields, but <TEXTAREA ...> and <SELECT ...> also create certain types. </FORM> End the form here. Of course, this form doesn't do much. You can type something into the one field, but that's it, nothing happens from there. In the next section, we expand the form a little. <APPLET CODE="MyApplet.class" WIDTH=200 HEIGHT=50> <PARAM NAME=TEXT VALUE="Hi There"> <P>Hi There!<P> </APPLET> Forms and Scripts Until scripting for web pages came along, CGIs were the only way to process form data. Now that Javascript is available on most web browsers, scripting provides a whole new avenue of neat ways to use forms. Unlike with CGI, forms that use scripts process the information immediately and can return the results right to the current web page. Script-based forms can also react to events other than just the user pressing a "Submit" button. An example of a script-only form is small form which sets the color of the current web page: this code produces this <FORM> <SELECT onChange="document.bgColor=this.options[this.selectedIndex].value" > <OPTION VALUE="FFFFFF">White <OPTION VALUE="FF0000">Red <OPTION VALUE="00FF00">Green <OPTION VALUE="0000FF">Blue </SELECT> </FORM> White A more extensive example is this form which calculates the properties of various geometric figures:
49
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Forms Tutorial

Forms Tutorial

Let's look at a very simple form:

this code produces this

<FORM ACTION="/cgi-bin/mycgi.pl"> favorite color: <INPUT NAME="color"> </FORM>

favorite color: rea

This form has all the required elements for a form:

<FORM ACTION="/cgi-bin/mycgi.pl">

Start the form here. The ACTION attribute, which is required with every <FORM ...> tag, is used with CGI, discussed below. <INPUT NAME="color">

Data entry field. <INPUT ...> creates most types of form fields, but <TEXTAREA ...> and <SELECT ...> also create certain types.

</FORM> End the form here.

Of course, this form doesn't do much. You can type something into the one field, but that's it, nothing happens from there. In the next section, we expand the form a little.

<APPLET CODE="MyApplet.class" WIDTH=200 HEIGHT=50>

<PARAM NAME=TEXT VALUE="Hi There">

<P>Hi There!<P>

</APPLET>

Forms and Scripts

Until scripting for web pages came along, CGIs were the only way to process form data. Now that Javascript is available on most web browsers, scripting provides a whole new avenue of neat ways to use forms. Unlike with CGI, forms that use scripts process the information immediately and can return the results right to the current web page. Script-based forms can also react to events other than just the user pressing a "Submit" button.

An example of a script-only form is small form which sets the color of the current web page:

this code produces this

<FORM> <SELECT onChange="document.bgColor=this.options[this.selectedIndex].value" > <OPTION VALUE="FFFFFF">White <OPTION VALUE="FF0000">Red <OPTION VALUE="00FF00">Green <OPTION VALUE="0000FF">Blue </SELECT> </FORM>

White

A more extensive example is this form which calculates the properties of various geometric figures:

Page 2: Forms Tutorial

Circumference and Radius of a Circle

radius:

circumference:

area:

Surface Area and Volume of a Cone

radius:

height:

surface area:

volume:

Surface Area and Volume of a Sphere

radius:

surface area:

volume:

This form also demonstrates that even a relatively simple script-based form requires lengthy script coding. Take a look at the source code for this form.

Forms and CGI

The original and still most popular use for forms is in conjunction with CGI (Common Gateway Interface). In the CGI way of doing things, the data the user enters is sent to the web server, where a program processes the data and returns the results. In other words, all the data is processed on the server, not in the web browser.

Let's expand our earlier example to show how to incorporate CGI:

<FORM ACTION="/cgi-bin/mycgi.pl"> favorite color: <INPUT name="favecolor"> <INPUT TYPE=SUBMIT VALUE="Submit"> </FORM>

which gives us

favorite color: Submit

Here's what the new pieces mean:

<FORM ACTION="/cgi-bin/mycgi.pl">

ACTION tells the browser where to send the data for processing (more on that shortly). ACTION is required with every form,

even forms that don't use CGI. <INPUT name="favecolor">

We've added the NAME attribute. NAME identifies each field, "names" it so it can be referred to later.

<INPUT TYPE=SUBMIT VALUE="Submit">

This <INPUT ...> tag creates the "submit" button, which the user presses to send the form to the web server.

That's the basic set up for a CGI form, but what happens after the user presses Submit? Consider, for example, this simple form:

Page 3: Forms Tutorial

Join our mailing list

Name:

E-mail:

Submit

Here's the chain of events when the user hits "Submit":

1. When the user presses Submit, the browser sends the form data to the web server. 2. The web server launches the CGI program which was written to process this form. 3. The CGI program does whatever it does with the data. The program might consult a database, perform calculations on the

data, use the data to add the user to a mailing list, whatever the programmer wants it to do. Whatever else the program does, it generates a web page using HTML so the user can see the results of submitting the form.

4. The CGI program passes the HTML back to the web server. 5. The web server passes the HTML back to the browser.

So there are three pieces to the CGI process: the form on your web page, the web server, and the CGI program. This guide deals with the first part: how to use HTML to make a form. Your web administrator handles the web server, and for a good guide on how to write CGIs, we recommend James Marshall's excellent (and short) CGI Made Really Easy.

NOTE: If you want to get started writing HTML forms but don't have a CGI set up yet, you can use our publicly available CGI at ../cgi-bin/mycgi.pl. This CGI will produce a web page of all the fields sent to it, so you can see if the forms work the way you intended. Most of the forms on the rest of this page will use this CGI.

Technically speaking there is no such thing as "a CGI". "CGI" is a standard protocol, not an actual implementation. However, it has become common to refer to a program which uses the CGI standard as "a CGI", and we will follow that custom here.

One of the reasons CGI is so popular is that the CGI program can be written in just about any programming language: C, C++, Perl (the most popular language for CGI), Visual Basic, etc. CGI was designed to allow great flexibility in processing the form data, while still allowing the results to be returned as HTML (or other formats, but HTML is the most popular).

Rollover Submit Image

HTML allows us to use images to create submit buttons for forms. Unfortunately, creating a rollover submit image can be a little more tricky. The technique described here allows you to create a rollover submit image using a script which does most of the work for you.

Suppose we want to use these two images to make a submit rollover. The first is the image which is displayed when the mouse is not over the image, the second when the mouse is over the image.

submit.out.gif

submit.over.gif

First, copy this script into your page. Copy as-is without changing anything:

Page 4: Forms Tutorial

<SCRIPT TYPE="text/javascript">

<!--

// copyright 1999-2001 Idocs, Inc. http://www .idocs.com/tags/

// Distribute this script freely, but keep this

// notice w ith the code.

var submitRolls = new Object();

function submitroll(src, oversrc, name)

{

this.src=src;

this.oversrc=oversrc;

this.name=name;

this.alt="Submit Query";

this.w rite=submitroll_w rite;

}

function submitroll_w rite()

{

var thisform = 'document.forms[' + (document.forms.length - 1) + ']';

submitRolls[this.name] = new Object();

submitRolls[this.name].over = new Image();

submitRolls[this.name].over.src = this.oversrc;

submitRolls[this.name].out = new Image();

submitRolls[this.name].out.src = this.src;

document.w rite

(

'<A onMouseOver="if (document.images)document.images[\'' + this.name + "'].src=su

' onMouseOut="if (document.images)document.images[\'' + this.name + "'].src=submi

' HREF="javascript:'

);

if (this.sendfield)

{

if (! this.sendvalue)

this.sendvalue = 1;

document.w rite(thisform, ".elements['", this.sendfield, "'].value='", this.sendvalue, "';"

}

document.w rite(thisform + '.submit();void(0);"');

if (this.msg)document.w rite(' onClick="return confirm(\'' , this.msg, '\')"');

document.w rite('>');

document.w rite('<IMG SRC="' + this.src + '" ALT="' + this.alt + '" BORDER=0 NAME="' + this.nam

if (this.height)document.w rite(' HEIGHT=' + this.height);

if (this.w idth)document.w rite(' WIDTH=' + this.w idth);

if (this.otheratts)document.w rite(' ' + this.otheratts);

document.w rite('></A>');

if (this.sendfield)

{

document.w rite('<INPUT TYPE=HIDDEN NAME="' + this.sendfield + '">');

document.forms[document.forms.length - 1].elements[this.sendfield].value='';

}

}

//-->

</SCRIPT>

1 2 3 4 5 6 7 8 9101112131415

<FORM ACTION="../cgi-bin/mycgi.pl"> email: <INPUT NAME="email"> <SCRIPT TYPE="text/javascript"> <!-- var sr = new submitroll("submit.out.gif","submit.over.gif","mysubmit"); sr.write(); //--> </SCRIPT> <NOSCRIPT> <INPUT TYPE=SUBMIT VALUE="Go!"> </NOSCRIPT> </FORM>

Page 5: Forms Tutorial

which gives us this form:

email:

Most of the form is as normal. Where we would have put the submit button we put some JavaScript instead. Our script has only two commands.

The first command at line 6 creates a new submitroll() object and takes three parameters. The first parameter

("submit.out.gif") sets the source for the image which is displayed when the mouse is not over. The second parameter

("submit.over.gif") sets the source for the image which is displayed when the mouse is over. The last parameter ("mysubmit") gives the image a nickname which is used by the script.

The next command at line 7 writes out the HTML and JavaScript to create the image.

We follow the script with a short <NOSCRIPT> element for browsers which don't have JavaScript.

This technique covers all the bases, creating a rollover submit image without a lot of hassle. In the next page we'll discuss a few optional settings you can add to the script.

Rollover Submit Image: Other Settings

By default, all the rollover submit script requires is the sources of the "over" and "out" images and a nickname for the image. The script allows you to set a few other optional settings as well:

<FORM ACTION="../cgi-bin/mycgi.pl" NAME="myform"> email: <INPUT NAME="email"> <SCRIPT TYPE="text/javascript"> <!-- var sr = new submitroll("submit.out.gif","submit.over.gif","mysubmit"); sr.alt="OK"; sr.width=60; sr.height=60; sr.otheratts="ALIGN=TOP"; sr.write(); //--> </SCRIPT> <NOSCRIPT> <INPUT TYPE=SUBMIT VALUE="Go!"> </NOSCRIPT> </FORM>

email:

The code here is almost the same as in our previous example. This time we've just added a few lines.

By default the alternate text for the image is Submit Query. In our example above, sr.alt="OK"; sets the alternate text as "OK" to match the text in the image.

sr.width=60; and sr.height=60; set the width and height of the image.

Finally, the script gives an opportunity to add some attributes to the <IMG ...> tag. In this the form looks better if the text field is aligned with the top of the image instead of the bottom so we add sr.otheratts="ALIGN=TOP";.

Page 6: Forms Tutorial

Image as a Reset Button

HTML allows you to use an image as a submit button, but it doesn't provide for images as reset buttons. We can work around that limitation, however, with a little JavaScript. The technique described here allows you to easily create a reset image button. This technique only requires you to write a few lines of code.

First, copy the following JavaScript exactly as-is into your web page. Don't change anything.

<SCRIPT TYPE="text/javascript"> <!-- // copyright 1999-2001 Idocs, Inc. http://www.idocs.com/tags/ // Distribute this script freely, but keep this // notice with the code. var resetRolls = new Object(); function resetimage(src) { this.src=src; this.confirm=true; this.alt="Reset"; this.write=resetimage_write; } function resetimage_write() { document.write('<A '); if (this.rollover) { if (! this.name) { alert('to create a rollover you must give the image a name'); return; } resetRolls[this.name] = new Object(); resetRolls[this.name].over = new Image(); resetRolls[this.name].over.src=this.rollover; resetRolls[this.name].out = new Image(); resetRolls[this.name].out.src=this.src; document.write( ' onMouseOver="if (document.images)document.images[\'' + this.name + '\'].src=resetRolls[\'' + this.name + '\'].over.src"' + ' onMouseOut="if (document.images)document.images[\'' + this.name + '\'].src=resetRolls[\'' + this.name + '\'].out.src"' ); } document.write(' HREF="javascript:'); if (this.confirm) document.write('if(confirm(\'Are you sure you want to reset?\'))'); document.write( 'document.forms[' + (document.forms.length - 1) + '].reset();void(0);">'); document.write('<IMG SRC="' + this.src + '" ALT="' + this.alt + '"'); document.write(' BORDER=0'); if (this.name)document.write(' NAME="' + this.name + '"'); if (this.height)document.write(' HEIGHT=' + this.height); if (this.width)document.write(' WIDTH=' + this.width); if (this.otheratts)document.write(' '+ this.otheratts); document.write('></A>'); } //--> </SCRIPT>

Now, suppose we want to use this image as our reset button: We'll create our form with this code:

Page 7: Forms Tutorial

<FORM ACTION="../cgi-bin/mycgi.pl"> <INPUT NAME="query"> <INPUT TYPE=IMAGE SRC="go2.gif" HEIGHT=22 WIDTH=50 ALT="go!" BORDER=0> <SCRIPT TYPE="text/javascript"> <!-- var ri = new resetimage("reset.gif"); ri.write(); //--> </SCRIPT> <NOSCRIPT><INPUT TYPE=RESET></NOSCRIPT> </FORM>

Which gives us this form:

In the previous section we showed you how to create a rollover submit image. In the next page we'll show you how to create a rollover reset image. We'll also explain how to set some of the optional settings.

Rollover Image as a Reset Button

The script in the previous page allows you to easily create a "reset image" button. As long as we're creating a reset image, it's only a small step to make into a rollover reset image. Here's how.

Suppose these are the two images we want to use for our rollover: and . We create the reset image the same way as in the previous example adding only two lines of code to make it a rollover:

<FORM ACTION="../cgi-bin/mycgi.pl"> <INPUT NAME="query"> <SCRIPT TYPE="text/javascript"> <!-- var sr = new submitroll("go2.gif","go2.over.gif","mysubmit"); sr.write(); //--> </SCRIPT> <SCRIPT TYPE="text/javascript"> <!-- var ri = new resetimage("reset.gif"); ri.name = "resetter"; ri.rollover = "reset.over.gif"; ri.write(); //--> </SCRIPT> <NOSCRIPT> <INPUT TYPE=RESET> </NOSCRIPT> </FORM>

Which gives us this form:

Page 8: Forms Tutorial

(You may notice that we also that we set the submit button as a rollover using the Rollover Submit Image technique.)

We set the "mouseout" image as the regular image for the reset. To add the rollover, we first give it the image a name. In our example we name the image "resetter" with the command ri.name = "resetter";. You must give the image a name or script will fail to generate the necesary code.

We then indicate the source of the "mouseover" image with the command ri.rollover = "reset.over.gif";.

Reset Image: Settings

The image reset provides for a some options on how the image is displayed.

<FORM ACTION="../cgi-bin/mycgi.pl"> <INPUT NAME="query"> <INPUT TYPE=IMAGE SRC="go2.gif" HEIGHT=22 WIDTH=50 ALT="go!" BORDER=0 ALIGN=TOP> <SCRIPT TYPE="text/javascript"> <!-- var ri = new resetimage("reset.gif"); ri.confirm=false; ri.alt="reset!"; ri.width=70; ri.height=22; ri.otheratts = "ALIGN=TOP"; ri.write(); //--> </SCRIPT> <NOSCRIPT> <INPUT TYPE=RESET> </NOSCRIPT> </FORM>

By default the script checks if the user really wants to reset the form (usually a good idea, see RESET). If for whatever reason you

don't want this confirmation then set the confirm property to false: ri.confirm=false;.

You can specify the width, height, and alternate text of the reset image with those corresponding properties: ri.alt="reset!";, ri.width=70;, and ri.height=22;.

Finally, if you have any HTML attributes you want added to the <IMG ...> tag you can set those with the otheratts property. In our example we set the alignment with ri.otheratts = "ALIGN=TOP";.

Sound Formats

There are many computer formats for sound, and theoretically any of them could be used in a web page. The three most popular formats (those most likely to work on your readers' machines) are WAVE, AU, and MIDI.

WAVE (Waveform Audio File Format, with the file extension .wav) was invented for Windows by Microsoft. AU (Audio File Format, file extension .au) was invented by NeXT and Sun. Both are now widely accepted on many platforms, and are common on web pages. WAVE and AU are like sound recordings... they reproduce recorded sounds (or computer generated sounds). They also tend to be big files for just a little sound. WAVE and AU files are good for a short sound effect such as a short greeting or perhaps a cow moo. (Notice that the size of that moo file is 21.5 KK for only about one second of sound.) There is also a recorded sound format called AIFF (Audio Interchange File Format), invented by Apple and SGI, which is widely supported, but is far less popular than AU and WAVE.

Page 9: Forms Tutorial

MIDI (Musical Instrument Digital Interface) is an entirely different concept. The MIDI file format is a series of commands such as "play middle C for .25 seconds". These sort of commands are very small, so one of the great advantages of MIDI files for your web page is that a lot of music can be packed in a small MIDI file. This rendition of "Hazy Shade of Winter" is only 16K but plays for over two minutes. The downside of MIDI is that it takes a real master to work any expressiveness into this electronic command-based format. MIDI music tends to have an uninteresting "easy listening" quality to it, making your web page seem like a dentist office.

A Special Problem with MIDIs

One particular problem with MIDI files on the web is common enough to merit special attention. You may find that when you try to download a MIDI file from your web site, your browser does not recognize what type of file it is. This can happen even though your browser understood the file when it was on your local hard drive. Here's what's going on in this situation. Every time a web server sends out a resource such as a web page, MIDI file, or whatever, it first sends an HTTP header to tell what kind of information is being sent. For example, when a web page is sent, the MIME type is text/html. The MIME type for MIDI is audio/midi. The server usually (but not always) determines the data type from the file extension. The standard file extensions for MIDI are ".mid" and ".midi". However, if the server doesn't recognize the extension, it won't send the correct MIME type. This is very often the problem with MIDI files on the web. (It's worth noting that this problem can actually happen with any type of media -- it just seems to happen very frequently with MIDIs.) MIDI has become popular enough that many people are using it on their web pages, but the web servers of the world have not all caught up and are sending bad mime types. Fortunately, this is an easy problem to solve. If you are having problems getting MIDIs from your web server, send a note like this to your web server administrator:

Could you configure the web server so that the mime type for file extensions .mid and .midi is audio/midi? Thanks! :-)

Background Sounds

A "background sound" is a sound that starts to play automatically when the web page is loaded.

Before you go any further, think hard: Do you really want to do this? Background sounds have a way of annoying people. There someone is, happily surfing the net, when suddenly their computer starts playing music for everyone to hear, perhaps everyone in the office area, who are now finding out that our formerly happy surfer isn't really working. That's not to say that background sounds are never a good idea... you may have noticed that we use one on this page. It just seemed appropriate for a page about sounds on web pages.

Now, assuming you've thought through the consequences of your actions, let's talk about how to put a background sound on your page. Unfortunately the browser industry and standards committees have not settled on a standard way of accomplishing this. Netscape allows background sounds through use of the <EMBED ...> tag. MSIE, Mosaic, and several other browsers use the

<BGSOUND ...> tag. You might at this point ask why you can't just use both and let each interpret its preferred tag. The problem is

that MSIE sometimes interprets the <EMBED ...> tag in addition to <BGSOUND ...> (depending on the particular installation) resulting in conflict and ugly error messages. This is the sort of thing that happens when there isn't a standard to follow.

With this lack-of-standards problem, the best to hope for is a situation that plays the sound in most situations, and in the other situations doesn't play the sound and doesn't give error messages. This can be accomplished using scripting, as in this example.

<SCRIPT TYPE="text/javascript"> <!-- var filename="hazy_shade_of_winter.mid"; if (navigator.appName == "Microsoft Internet Explorer") document.writeln ('<BGSOUND SRC="' + filename + '">'); else if (navigator.appName == "Netscape") document.writeln ('<EMBED SRC="' + filename + '" AUTOSTART=TRUE WIDTH=144 HEIGHT=60><P>'); // --> </SCRIPT> <NOSCRIPT> <BGSOUND SRC="hazy_shade_of_winter.mid"> </NOSCRIPT>

The code says this:

1. If the current browser is MSIE then write out a <BGSOUND ...> tag.

2. Else, if the current browser is Netscape then write out an <EMBED ...> tag.

3. Then in the <NOSCRIPT> section, browsers that don't understand scripting will see the <BGSOUND ...> tag. Several

browsers that don't understand scripting do understand <BGSOUND ...>. Also, browsers that have scripting turned off but

do understand <BGSOUND ...> will also see this tag. Of course, browsers that have scripting turned off but don't

understand <BGSOUND ...> will have no sound at all. Again, that's the price being paid for lack of standards. At least they won't fail with an ugly error message.

Page 10: Forms Tutorial

That's kind of complicated, isn't it? Well, that's the problem with this sort of kludge: you have to try to anticipate all the situations and avoid the nasty ones. Hopefully in the foreseeable future the browser makers will correct this problem.

Linking to Sounds

Happily, linking to a sound is a lot easier than setting a background sound. Just link to the sound just like you would link to a web page:

this code produces this

<A HREF="laugh.wav">here's a good laugh</A> here's a good laugh

<BGSOUND ...>

Usage Recommendation

Use this tag conservatively if at all. It's very easy to annoy people with background sounds.

• SRC: URL of the sound • LOOP: how many times to play the sound

Before you read any further about this tag, please read the section about background sounds, which discusses how to combine this tag (which Netscape doesn't understand) with a Netscape-friendly <EMBED ...> tag.

<BGSOUND ...>, MSIE, tells the browser to play a particular sound when the page is loaded.

this code produces this

<BGSOUND SRC="helloo.wav"> the background sound on this page

This tag was the cause of some annoyance for users of MSIE versions 1 and 2 because it could not be turned off, but the STOP button now stops the playing.

Attribute for <BGSOUND ...> SRC

SRC gives the location of the sound to play:

this code produces this

<BGSOUND SRC="helloo.wav"> the background sound on this page

Attribute for <BGSOUND ...> LOOP = INFINITE | number of loops

Usage Recommendation

Use with great caution. This is a major way to annoy people.

LOOP says how many times to loop the background sound. LOOP can either have a finite value (1,2,3 or some other number) or INFINITE which tells the browser to play the sound over and over forever. LOOP can be very annoying. Use it sparingly, or better yet, not at all.

Page 11: Forms Tutorial

this code produces this

<BGSOUND SRC="helloo.wav" LOOP=5> this page is really annoying

this page

<BGSOUND SRC="helloo.wav" LOOP=INFINITE> this page is really, REALLY annoying

this page

<SOUND ...>

Usage Recommendation

use <BGSOUND ...> instead

A rare example of a "Mosaic Only" tag. <SOUND ...> works just like <BGSOUND ...>. Use <BGSOUND ...> instead.

Usage Recommendation

use <BGSOUND ...> instead

A rare example of a "Mosaic Only" tag. <SOUND ...> works just like <BGSOUND ...>. Use <BGSOUND ...> instead.

<HYPE>

Usage Recommendation

don't use it

<HYPE> is an "easter egg", an obscure feature hidden in a program for no other purpose than to make the programmers giggle

themselves silly. In some versions of Netscape, <HYPE> plays a silly sound.

Frames Tutorial

Page 12: Forms Tutorial

Let's look at a basic example of how frames work:

The frameset file is the file you point your browser to.

The frameset file uses <FRAMESET ...> and <FRAME ...> to tell the

browser to go get more files to put on the page.

The browser goes out again and retrieves the files which will appear

on the page.

The browser puts all the files on one page in separate rectangles

("frames"). The user never sees anything from the original frameset

file.

Think of frames as creating a "table of documents" on the page. Like a table, a group of frames has rows and columns. Each cell of the table contains a document which is stored in a separate file. <FRAMESET ...> defines the beginning and end of the table, and how many rows and columns that table will have. <FRAME ...> defines what will go into each cell ("frame") of the table.

Let's look in more detail at the example above. The entire contents of basicframeset.html (the frameset file) look like this:

This code ... creates this page (here's the real thing)

Page 13: Forms Tutorial

<HTML> <HEAD> <TITLE>A Basic Example of Frames</TITLE> </HEAD> <FRAMESET ROWS="75%, *" COLS="*, 40%"> <FRAME SRC="framea.html"> <FRAME SRC="frameb.html"> <FRAME SRC="framec.html"> <FRAME SRC="framed.html"> <NOFRAMES> <H1>No Frames? No Problem!</H1> Take a look at our <A HREF="basic.noframes.html">no-frames</A> version. </NOFRAMES> </FRAMESET> </HTML>

Here's a line-by-line explanation of each piece of code for the frames:

<FRAMESET

Start the "table of documents". ROWS="75%, *"

The table should have two rows. The first row should take up 75% of the height of the page, the second should take up the

rest. COLS="*, 40%">

The table should also have two columns. The second column should take up 40% of the width of the page, the first column

should take up the rest. <FRAME SRC="framea.html"> <FRAME SRC="frameb.html"> <FRAME SRC="framec.html"> <FRAME SRC="framed.html">

Put the four files into the frames.

<NOFRAMES> ... </NOFRAMES> Every framed page should have a no-frames alternative. The <NOFRAMES> content should go inside the outermost

<FRAMESET ...> tag, usually just before the last </FRAMESET>. The most efficicent method for no-frames content is to link

to a page which is specifically designed for no-frames. </FRAMESET>

End the frameset.

There are several other aspects of frames to note from this example:

• <FRAMESET ...> is used instead of the <BODY ...> tag. The frameset file has no content which appears on the page, so

it has no need for <BODY ...>, which designates the content of the page. In fact, if you use <BODY ...> (except inside

<NOFRAMES>), the frames will not appear. Tags in <HEAD>, including <TITLE>, still have their intended effects.

• Rows and columns are described by a list of widths or heights. For example COLS="25%, *, 40%" says that there will be

three columns. The first column takes up 25% of the width of the page, the third column takes up 40% of the width of the

page, and the asterisk ("*") means "whatever is left over". See COLS and ROWS for more details.

• You do not explicitly designate the start and ending of each row. The browser keeps adding frames until it reaches the

number designated by COLS, then starts another row.

Page 14: Forms Tutorial

Nested Framesets

Let's move now to a more real world example, and a few more techniques for using frames. One of the most popular uses for frames is the "title bar and side menu" method. We'll use as an example a page of recipes, pictured at right. The title of the page, "Great Recipes" stays stationary in a frame at top, a contents list is on the left, and the recipes themselves are in the large box on the right. As you click on the name of a recipe in the contents list, that recipe appears on the right. Go ahead and try out the real page. (We're sorry if these recipes make you hungry. They did us. These recipes come from the wonderful vegetarian recipe site Veggies Unite!.)

Remember that a frameset is like a "table of documents" with rows and columns. The recipes page, however, has one column on top, but two on bottom. This is done by nesting framesets, putting one frameset inside another.

Here's the code for the frameset file for the recipes page:

<HTML> <HEAD> <TITLE>Great Recipes</TITLE> </HEAD> <FRAMESET ROWS="15%,*"> <FRAME SRC="recipetitlebar.html" NAME=TITLE SCROLLING=NO> <FRAMESET COLS="20%,*"> <FRAME SRC="recipesidebar.html" NAME=SIDEBAR> <FRAME SRC="recipes.html" NAME=RECIPES> </FRAMESET> <NOFRAMES> <H1>Great Recipes</H1> No frames? No Problem! Take a look at our <A HREF="recipes.html">no-frames</A> version. </NOFRAMES> </FRAMESET> </HTML>

Page 15: Forms Tutorial

Targeting Frames

Each frame is given a name using <FRAME NAME="...">. These names uniquely identify each frame. Using these names, links in other frames can tell the browser which frame the link targets.

For example, this code creates a framed page, naming the frames TITLE, SIDEBAR, and MAIN:

<FRAMESET ROWS="15%,*"> <FRAME SRC="tfetitle.html" NAME=TITLE SCROLLING=NO MARGINHEIGHT=1> <FRAMESET COLS="20%,*"> <FRAME SRC="tfesidebar.html" NAME=SIDEBAR> <FRAME SRC="tfemain.html" NAME=MAIN> </FRAMESET> <NOFRAMES>NOFRAMES stuff </NOFRAMES> </FRAMESET>

To target one of these frames, the link should have a TARGET attribute set to the name of the frame where the linked page should

appear. So, for example, this code creates a link to tfetacos.html and targets that link to the MAIN frame:

this code produces this

<A HREF="tfetacos.html" TARGET=MAIN>my link</A> the link in this page

Targeting the Whole Window

Eventually in a framed site you want to "break out"... link to a page and have that page take over the entire window. To create this sort of link, we add TARGET="_top" to the <A ...> tag:

this code produces this

<A HREF="wwtarget.html" TARGET="_top"> the link in this page

In the previous example we used TARGET to refer to a frame

we had named MAIN. In this example, however, we refer to a

frame we never named: "_top". We can do this because the outermost frame (that is, the entire window) is already named "_top". "_top" is a reserved name which is automatically given to the entire window. So when we say TARGET="_top", we are saying "put the new web page in the entire window". Note that "_top" needs to be in all lower-case, it should have quotes around it, and don't forget the underscore ("_").

No matter what the other frames are named,

the entire window is always named "_top"

Page 16: Forms Tutorial

Popup Windows: The Basics

We'll begin the tutorial by creating a basic popup window. The technique described here addresses all the major issues in popups. The popup always comes to the front. Different links can target the same popup. The code is simple and easily modified. Everything for the rest of the turorial is a variation on the theme described here. The code in this page creates a popup that is opened from a link. In this section we'll show the code with just the minimal description you need to get it going. For more details see Under the Hood: Details of the Popup Script.

First, copy this script into the <HEAD> section of your page:

<SCRIPT TYPE="text/javascript"> <!-- function popup(mylink, windowname) { if (! window.focus)return true; var href; if (typeof(mylink) == 'string') href=mylink; else href=mylink.href; window.open(href, windowname, 'width=400,height=200,scrollbars=yes'); return false; } //--> </SCRIPT>

For now we'll skip the details of how the script works, (see Under the Hood: Details of the Popup Script for a line-by-line description), and move to the next step. The script above opens the popup, but something needs to run the script. The most common situation is that the script is run when the user clicks on a link. A link like the following would run the script:

<A HREF="popupbasic.html" onClick="return popup(this, 'notes')">my popup</A>

which creates this link:

my popup

Most of the link is as usual. The URL of the page being linked to is in the HREF attribute. We've added an additional attribute called

onClick. Copy the code as it is into your link, with only a small modification. The second argument of the popup() -- 'notes' -- indicates name of the popup window. Every popup window should have its own unique name. Be sure to put the name in single quotes (''). So if you want to name the popup 'stevie' then this would be the code:

<A HREF="popupbasic.html" onClick="return popup(this, 'stevie')">my popup</A>

Read This Next Part Or You'll Go Insane Trying to Figure Out Why Your Popup Doesn't Work

A small but crucial point is often overlooked. The command in onClick must begin with return or the script won't work. Be sure to

start the command with return like this:

onClick="return popup(this, 'notes')"

And don't put a space in the page name between the single quotes. If you do, the link will act just like a regular link.

<EMBED ...>

Usage Recommendation

use it, but don't rely on it

• SRC: URL of resource to be embedded

• WIDTH: width of area in which to show resource

• AUTOSTART: if the sound/movie should start automatically

• LOOP: how many times to play the sound/movie

Page 17: Forms Tutorial

• HEIGHT: height of area in which to show resource

• ALIGN: how text should flow around the picture

• NAME: name of the embedded object

• PLUGINSPAGE: where to get the plugin software

• PLUGINURL: where to get the JAR archive for

automatic installation

• HIDDEN: if the object is visible or not

• HREF: make this object a link

• TARGET: frame to link to

• PLAYCOUNT: how many times to play the sound/movie

• VOLUME: how loud to play the sound

• CONTROLS: which sound control to display

• CONTROLLER: if controls should be displayed

• MASTERSOUND: indicates the object in a sound group with

the sound to use

• STARTTIME: how far into the sound to start and stop

• ENDTIME: when to finish playing

<EMBED ...> puts a browser plugin in the page. A plugin is a special program located on the client computer (i.e. not on your web

server) that handles its own special type of data file. The most common plugins are for sounds and movies. The <EMBED ...> tag gives the location of a data file that the plugin should handle.

In its simplest use, <EMBED ...> uses the SRC attribute to indicate the location of the plugin data file, and usually also gives a WIDTH and HEIGHT of the plugin area. For example, the following code embeds a MIDI file of the 1812 Overture in the page:

this code produces this

<EMBED SRC="../graphics/sounds/1812over.mid" HEIGHT=60 WIDTH=144>

<EMBED ...> is not a part of the HTML 4 or xHTML 1 specifications, but it is still widely supported by modern browsers. Unlike other

tags, the attributes used by <EMBED ...> depend on the type of plugin being used (this odd free-attribute concept is why <EMBED ...> has been rejected by the HTML standards makers).

The only required attribute for <EMBED ...> is SRC, so let's begin there.

Attribute for <EMBED ...> SRC = "text string"

SRC is the one required attribute for SRC. SRC indicates where to get the media object to be embedded.

this code produces this

<EMBED SRC="../graphics/sounds/1812over.mid" HEIGHT=60 WIDTH=144>

Attributes for <EMBED ...> WIDTH = "width expression" HEIGHT = "height expression"

For such a simple concept -- the height and width of the embedded object -- choosing values for the HEIGHT and WIDTH attributes can be quite a thorny problem. Unlike images such as GIF and JPEGs, embedded objects do not necessarily have an inherent dimensions. Different browsers render different media types differently, and make different decisions about what to do if the object isn't exactly the height they want. Unfortunately leaving out the HEIGHT and WIDTH attributes is not an option. They are required and we have run across a few plugins that give nasty error messages if these attributes are missing

For sounds, try HEIGHT and WIDTH. These are the Netscape's preferred sizes, and MSIE adjusts to them well. There are different

preferred sizes if you use some of the odd controls Netscape allows. See CONTROLS for more details.

Page 18: Forms Tutorial

For movies, try setting HEIGHT to 30 pixels greater than the height of the movie, the WIDTH to just six greater:

this code produces this

<EMBED SRC="../graphics/heart.avi" HEIGHT=144 WIDTH=118 >

For other types of plugins, check the documentation, and experiment with different dimensions on different browsers.

Attribute for <EMBED ...> NAME = "text string"

NAME indicates the name of the embedded object. In most cases this attribute is not needed. However, some types of plugins can be controlled using JavaScript, or can communicate with each other, and those cases NAME comes in handy.

For example, the following code uses Netscape's LiveConnect features to play "hello" when the Hello link is clicked. If the browser is something beside Netscape, then the link works as a regular link. The sound will play a little sooner with Netscape, however, because it has already been downloaded. Note also that Netscape requires that if you use the NAME attribute you must also use

MASTERSOUND.

this code produces this

<EMBED SRC="../graphics/sounds/helloo.wav" HEIGHT=144 WIDTH=166 NAME=MySound MASTERSOUND HIDDEN > <SCRIPT TYPE="text/javascript"> <!-- function soundplay() { if (navigator.appName == "Netscape") { document.MySound.play(false) return false; } else return true; } //--> </SCRIPT> <A HREF="../graphics/sounds/helloo.wav" onClick="return soundplay()" >Hello!</A>

Hello!

Attribute for <EMBED ...> PLUGINSPAGE = "URL"

If the browser doesn't have the necessary software to run the plugin indicated in the <EMBED ...> tag, PLUGINSPAGE indicates the URL where the browser can get the software. It's a good idea to include this attribute for any plugin you use that isn't for the most common media types (MIDI, AVI, WAV).

Page 19: Forms Tutorial

For example, suppose we use a plugin which has the media type "whack/slack". (There isn't really any such type, this is just an example.) We could use the following <EMBED ...> tag to indicate the URL of where to get the plugin software.

this code produces this

<EMBED SRC="/cgi-bin/whack.slack.cgi" HEIGHT=170 WIDTH=150 PLUGINSPAGE="WhackSlackPlugin.html" >

If the browser has not already prompted you to retrieve the plugin

software, and if you have the type of browser which supports plugins, try

clicking on the plugin space above.

Attribute for <EMBED ...> PLUGINURL

PLUGINURL is used by Netscape Communicator's JAR Installation Manager. PLUGINURL points to a "JAR archive" which is a resource used to automatically install the plugin (so they say, I've had all kinds of problems with Netscape's "automatic" stuff). JAR archives are a special type of compressed files originally used for Java; see <APPLET ARCHIVE="...">.

Attribute for <EMBED ...> HIDDEN = FALSE | TRUE

HIDDEN indicates if the embedded object is visible or not. FALSE is the default.

this code produces this

<EMBED SRC="../graphics/sounds/helloo.wav" HEIGHT=60 WIDTH=144 HIDDEN=TRUE >

(embedded object is not visible)

<EMBED SRC="../graphics/sounds/helloo.wav" HEIGHT=60 WIDTH=144 HIDDEN=FALSE >

<EMBED SRC="../graphics/sounds/helloo.wav" HEIGHT=60 WIDTH=144 > <!-- this example doesn't use HIDDEN at all -->

(same as TRUE)

The first example results in an unusable object, because the user cannot start it in any way. However, if we add the AUTOSTART attribute, we get an invisible "background sound".

this code produces this

<EMBED SRC="../graphics/sounds/helloo.wav" HEIGHT=60 WIDTH=144 HIDDEN=TRUE >

this page

See the page on background sounds for more details on the best way to put background sounds on your web page.

Page 20: Forms Tutorial

Attributes for <EMBED ...> HREF = "URL" TARGET = "text string"

Usage Recommendation

don't use it

HREF and TARGET allow you to make the media object into a hyperlink. They work just like their counterparts <A HREF="..."> and

<A TARGET="...">. Note that you have to click somewhere besides the controls area to follow the link. The use of these attributes in <EMBED ...> is an MSIE extension.

this code produces this

<EMBED SRC="../graphics/clickme.avi" HREF="../" AUTOSTART=TRUE LOOP=TRUE WIDTH=115 HEIGHT=60 CONTROLLER=FALSE ><BR> <A HREF="../">Home Page</A>

Home Page

HREF can also be used with a sound, but because the user has to click somewhere besides the controls to follow the link, it is hopelessly difficult to communicate that the sound is a link:

this code produces this silly link

Click in the sound area but not in the controls to go to the home page <EMBED SRC="../graphics/sounds/helloo.wav" HREF="../" HEIGHT=100 WIDTH=144 >

Click in the sound area but not in the controls to go to the home

page

HREF used in <EMBED ...> is probably just getting too fancy. It only works with MSIE, and because it is so unusual, most users won't realize the movie is a link. This is one trick it is probably best to avoid.

Attribute for <EMBED ...> AUTOSTART = TRUE | FALSE

AUTOSTART (which works with both sounds and movies) indicates if the media clip should start automatically when it is loaded. TRUE indicates it should, FALSE (the default) says it shouldn't.

this code produces this

<EMBED SRC="../graphics/sounds/helloo.wav" AUTOSTART=TRUE WIDTH=144 HEIGHT=60 >

this page

Page 21: Forms Tutorial

Attribute for <EMBED ...> LOOP = TRUE | FALSE | # of loops

LOOP indicates how many times to play the sound or movie. In general, LOOP indicates if the sound or movie should (TRUE) or should not (FALSE) loop continuously.

Sounds

For sounds, both MSIE and Netscape recognize TRUE and FALSE. FALSE is the default.

this code produces this

<EMBED SRC="../graphics/sounds/helloo.wav" LOOP=FALSE HEIGHT=60 WIDTH=144 >

<EMBED SRC="../graphics/sounds/helloo.wav" LOOP=TRUE HEIGHT=60 WIDTH=144 >

Netscape also allows you to loop a finite number of times. (For MSIE use PLAYCOUNT) This code tells Netscape to play the sound three times. MSIE plays the sound continuously.

this code produces this

<EMBED SRC="../graphics/sounds/helloo.wav" LOOP=3 HEIGHT=60 WIDTH=144 >

You can combine this with MSIE's PLAYCOUNT attribute (which in MSIE takes precedence over LOOP) to tell both browsers to loop three times:

this code produces this

<EMBED SRC="../graphics/sounds/helloo.wav" LOOP=3 PLAYCOUNT=3 HEIGHT=60 WIDTH=144 >

Movies

LOOP can be set to TRUE or FALSE for movies.

this code produces this

<EMBED SRC="../graphics/heart.avi" LOOP=FALSE HEIGHT=144 WIDTH=117 >

<EMBED SRC="../graphics/heart.avi" LOOP=TRUE

Page 22: Forms Tutorial

HEIGHT=144 WIDTH=117 >

We have found in researching LOOP that Netscape has several inconsistencies among media types. For example, we have not been

able to get MPEGs for loop reliably. As with everything involving <EMBED ...>, be careful what you rely on.

.................................................................................................................................................................

<FORM ...>

Usage Recommendation

use it

• ACTION: URL of the CGI program

• METHOD: how to transfer the data to the CGI

• NAME: name of this form

• ENCTYPE: what type of form this is

• TARGET: what frames to put the results in

• onSubmit: script to run before the form is submitted

• onReset: script to run before the form is reset

<FORM ...> indicates the beginning of a form. All other form tags go inside <FORM ...>. In its simplest use, <FORM ...> can be used without any attributes:

this code produces this

<FORM> name: <INPUT><BR> email: <INPUT> </FORM>

name:

email:

Most forms require either the ACTION or NAME attributes to do anything meaningful. (The <FORM ...> attribute is always required,

but not necessarily used in every situation.) For example, to make this form work, we'll add the <FORM ACTION="..."> attribute,

which indicates the CGI program to send the form data to. We'll also use NAME in the <INPUT ...> tags, and add a Submit button:

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> name: <INPUT NAME=realname><BR> email: <INPUT NAME=email><BR> <INPUT TYPE=SUBMIT> </FORM>

name:

email:

Submit Query

NAME is useful when you want to use scripting

Attribute for <FORM ...> ACTION = "URL"

Usage Recommendation

Page 23: Forms Tutorial

use it

ACTION gives the URL of the CGI program which will process this form. For example, the CGI program "MyCGI" is located at ../cgi-bin/mycgi.pl (you can go directly to that URL). This form uses "MyCGI":

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> favorite color: <INPUT NAME=COLOR><BR> <INPUT TYPE=SUBMIT> </FORM>

favorite color:

Submit Query

When you click submit, your browser sends the form data to the CGI indicated in ACTION. See Forms and CGI for more about CGI

Attribute for <FORM ...> METHOD = GET | POST

Usage Recommendation

use it

METHOD specifies the method of transferring the form data to the web server.

METHOD can be either GET or POST. Each method has its advantages and disadvantages.

Take a look at what is actually sent to the web

server with each method

Your Ad Here

METHOD = GET

GET sends the data as part of the URL. For example, suppose you enter the value "West Rochester" in this form below:

this code produces this

<FORM METHOD=GET ACTION="../cgi-bin/mycgi.pl"> town: <INPUT NAME="town"><BR> <INPUT TYPE=SUBMIT> </FORM>

town:

Submit Query

The value entered in the "town" field is tacked on to the end of the CGI's URL like this:

../cgi-bin/mycgi.pl?town=West+Rochester

When the form data (or "query data") is added to the end of the URL it is "URL encoded" so that the data can be used in a standard URL. The neat thing about URL encoding is that each different query to the CGI has a different URL. Those unique URLs can be used directly in links without any form being involved. For example, the URL above can be used to create a link to exactly the same CGI results:

<A HREF="../cgi-bin/mycgi.pl?town=West+Rochester">West Rochester</A>

which creates this link: West Rochester.

Page 24: Forms Tutorial

The amount of data that can be sent with a URL is limited. GET is good for short forms (ten or fewer fields and no <TEXTAREA ...> or file uploads).

METHOD = POST

POST is the preferred method for sending lengthy form data. When a form is submitted POST the user does not see the form data that was sent. For example, this form uses POST:

<FORM METHOD=POST ACTION="../cgi-bin/mycgi.pl">

which gives us a form like this (go ahead and submit it):

name: George the

email: george@wh

preferences:

doesn't smoke

hates anchovies

reads Shakespeare

washes daily

romantic walks on the beach

romantic walks in Brooklyn

loves dogs

loves cats

loves iguanas

Now tell us a little about yourself:

I w as born in the house my

father built. I w as raised on a

farm w ith 13,000 acres of

oats, and now I

hate oatmeal. Much prefer the

crackly taste of w heat. I'm

looking for a w ife w ho loves

Send It

Attribute for <FORM ...> NAME = "text string"

Usage Recommendation

use it

NAME gives a name to the form. This is most useful in scripting, where you frequently need to refer to the form in order to refer to the

element within the form. For example, this reduced version of our geometry calculating script uses NAME to refer to the form which holds the radius field:

<SCRIPT> <!-- function Circle_calc_ii() { var CircleRadius = document.MyCircleForm.Circle_radius.value; if (CircleRadius >= 0) { document.MyCircleForm.Circle_circumference.value = 2 * Math.PI * CircleRadius ; document.MyCircleForm.Circle_area.value = Math.PI * Math.pow(CircleRadius, 2) ; } else { document.MyCircleForm.Circle_circumference.value = ""; document.MyCircleForm.Circle_area.value = ""; } } // --> </SCRIPT>

Page 25: Forms Tutorial

<FORM NAME="MyCircleForm"> <TABLE BORDER CELLPADDING=3> <TR> <TD><NOBR>radius: <INPUT NAME="Circle_radius" SIZE=4></NOBR></TD> <TD><INPUT TYPE=BUTTON OnClick="Circle_calc_ii(this.form);" VALUE="calculate"></TD> <TD ALIGN=RIGHT BGCOLOR="#AACCFF"> <NOBR>circumference: <INPUT NAME="Circle_circumference" SIZE=9></NOBR><BR> <NOBR>area: <INPUT NAME="Circle_area" SIZE=9></NOBR></TD> </TR> </TABLE> </FORM>

radius:

circumference:

area:

It is possible to refer to the form without using NAME, and sometimes it makes for less work. To give the above example we needed to create the whole script all over again. Instead, we could use the original CircleAreaCalc function at the top of this page, which allows us to pass in the form object as an argument (using this.form), obviating the need for NAME:

<FORM><!-- note there is no NAME atttibute --> <TABLE BORDER CELLPADDING=3> <!-- circumference and radius of a circle --> <TR> <TD><NOBR>radius: <INPUT NAME="Circle_radius" SIZE=4></NOBR></TD> <TD><INPUT TYPE=BUTTON OnClick="Circle_calc(this.form);" VALUE="calculate"></TD> <TD ALIGN=RIGHT BGCOLOR="#AACCFF"> <NOBR>circumference: <INPUT NAME="Circle_circumference" SIZE=9></NOBR><BR> <NOBR>area: <INPUT NAME="Circle_area" SIZE=9></NOBR></TD> </TR> </TABLE> </FORM>

which gives us

radius:

circumference:

area:

Another much worse way to refer to the form without giving it a name is to use the form's index in the forms array. If our form were the first form on this web page, we could refer to it like this:

var CircleRadius = parseFloat(document.forms[0].Circle_radius.value);

That would require keeping track of how many forms down on the page it is, and on a page like this that would be way too much trouble.

Attribute for <FORM ...> ENCTYPE = "multipart/form-data" | "application/x-www-form-urlencoded" | "text/plain"

Usage Recommendation

use it

In most cases you will not need to use this attribute at all. The default value (i.e. if you don't use this attribute at all) is "application/x-www-form-urlencoded", which is sufficient for almost any kind of form data. The one exception is if you want to do file uploads. In that case you should use "multipart/form-data". See file uploads for more details.

Page 26: Forms Tutorial

ENCTYPE determines how the form data is encoded. Whenever data is transmitted from one place to another, there needs to be an agreed upon means of representing that data. Music is translated into written music notation, English is written using letters and punctuation. Similarly, there needs to be an agreed on way of presenting the form data so it's clear that, for example, there is a field called "email" and its value is "[email protected]".

Attribute for <FORM ...> TARGET = "_blank" | "_parent" | "_self" | "_top" | frame name

TARGET indicates which frame in a set of frames to send the results to, and works just like <A TARGET="...">. This attribute can be used so that the form is always visible even as the form results are displayed and redisplayed.

this code produces this

<FORM TARGET="TargetFrame" ACTION="../cgi-bin/mycgi.pl">

this page

Attribute for <FORM ...> onSubmit = "script command(s)"

Usage Recommendation

use it, but don't rely on it

onSubmit is a scripting event that occurs when the user attempts to submit the form to the CGI. onSubmit can be used to do some

error checking on the form data, and to cancel the submit if an error is found. For example, this <FORM ...> tag calls a Javascript function to check the form data:

<FORM ACTION="../cgi-bin/mycgi.pl" NAME="testform" onSubmit="return TestDataCheck()" >

Note that in order to cancel the submit event, the onSubmit should be in the form onSubmit="return expression". "return" indicates that the value of the expression should be returned to the submit routine. If the expression evaluates to false, the submit routine is cancelled; if it is true, the submit routine goes forward.

Let's look at the full code for our example. Consider a form that a technician uses to enter how many production units have been tested, and how many units passed the tests. For a form like this we might want to check:

• if one or more units were tested

• if zero or more units were passed

• if no more units were passed than were tested

Here is the full code to do this:

<SCRIPT TYPE="text/javascript"> <!-- // check that they entered an amount tested, an amount passed, // and that they didn't pass units than they more than tested function TestDataCheck() { var qtytested = parseInt(document.testform.qtytested.value); var qtypassed = parseInt(document.testform.qtypassed.value); var returnval; if ( (qtytested >= 1) && (qtypassed >= 0) && (qtytested >= qtypassed)) returnval = true;

Take a look at what is actually sent to the web

server with each ENCTYPE

Page 27: Forms Tutorial

else { alert("must enter the quantity tested and that amount or fewer for quantity passed"); returnval = false; } return returnval; } // --> </SCRIPT> <FORM ACTION="../cgi-bin/mycgi.pl" NAME="testform" onSubmit="return TestDataCheck()" > units tested: <INPUT NAME="qtytested" SIZE=3><BR> units passed: <INPUT NAME="qtypassed" SIZE=3><P> <INPUT TYPE=SUBMIT VALUE="Submit"> </FORM>

which gives us this form:

units tested:

units passed:

Submit

onSubmit is a good way to prescreen the data on a form before it is submitted to the CGI, but like anything Javascript, it shouldn’t be relied on. Be sure to error check the data in your CGI program also.

Attribute for <FORM ...> onReset = "script command(s)"

onReset runs a script when the user resets the form. If onReset returns false, the reset is cancelled. Often when people hit reset they don't really mean to reset all their typing, they just hit it accidentally. onReset gives them a chance to cancel the action.

This code checks with if the user really wants to reset the form:

<FORM ACTION="../cgi-bin/mycgi.pl" onReset="return confirm('Do you really want to reset the form?')" > <INPUT TYPE=TEXT NAME="query"> <INPUT TYPE=SUBMIT> <INPUT TYPE=RESET> </FORM>

This gives us this form:

Submit Query Reset

INPUT ...>

Usage Recommendation

use it

• TYPE: what type of field

• NAME: name of this form field

• HSPACE: horizontal distance between the picture and the text

• READONLY: the value of this field cannot be changed

Page 28: Forms Tutorial

• VALUE: initial or only value of this field

• SIZE: how wide the text field should be

• MAXLENGTH: maximum number of characters

• CHECKED: check this checkbox or radio button

• BORDER: border around image

• SRC: URL of image

• ALT: text to show if you don't show the picture

• LOWSRC: a version of the picture that isn't such a

big file

• WIDTH: width of image

• HEIGHT: height of image

• ALIGN: how text should flow around the picture

• VSPACE: vertical distance between the picture and

the text

• DISABLED: don't let the user do anything with this field

• ACCESSKEY

• TABINDEX: tab order

• LANGUAGE: scripting language to use

• onClick: when the user clicks here

• onChange: when this field is changed

• onFocus: when this field gets the focus

• onBlur: when this field loses the focus

• onKeyPress: script to run when a key is pressed

• onKeyUp: script for when a key goes up while the field has the

focus

• onKeyDown: script for when a key goes down while the field has

the focus

• AUTOCOMPLETE: If the browser should use autocompletion for

the field

<INPUT ...> creates the data entry fields on an HTML form. (Well, it creates most types of fields, <TEXTAREA ...> and <SELECT

...> also create some, as does the new <BUTTON ...> tag.) The TYPE attribute establishes what type of field the input is creating.

The other <INPUT ...> attributes affect different types of inputs different ways (or not at all). So let's jump straight into the TYPE attribute and look at the different types of input fields.

Attribute for <INPUT ...> TYPE = TEXT | CHECKBOX | RADIO | PASSWORD | HIDDEN | SUBMIT | RESET | BUTTON | FILE | IMAGE

TYPE establishes what type of data entry field this is. The <INPUT ...> tag has ten different types of fields (the <TEXTAREA ...>, <SELECT ...>, and <BUTTON ...> tags create the other types).

TYPE = TEXT

TEXT creates a text entry field (the most popular type of data entry field):

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> name: <INPUT TYPE=TEXT NAME="realname"> <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

name:

submit

TEXT is the default input type (if you want a text field, you don't even need to use the TYPE attribute).

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> <!-- Note absence of TYPE attribute --> name: <INPUT NAME="realname"> <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

name:

submit

Page 29: Forms Tutorial

The behavior of TEXT fields can be modified using these attributes:

• VALUE: set an initial value for the field

• SIZE: how wide the field should be

• MAXLENGTH: the maximum number of characters the user can enter

TYPE = TEXT

TEXT creates a text entry field (the most popular type of data entry field):

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> name: <INPUT TYPE=TEXT NAME="realname"> <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

name:

submit

TEXT is the default input type (if you want a text field, you don't even need to use the TYPE attribute).

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> <!-- Note absence of TYPE attribute --> name: <INPUT NAME="realname"> <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

name:

submit

The behavior of TEXT fields can be modified using these attributes:

• VALUE: set an initial value for the field

• SIZE: how wide the field should be

• MAXLENGTH: the maximum number of characters the user can enter

TYPE = RADIO

RADIO is used to create a series of choices of which only one can be selected. The term "radio button" comes from the buttons for the radio in an automobile, where selecting one radio station automatically de-selects all the others. HTML radio buttons are created by using several <INPUT TYPE=RADIO> buttons, all with the same name, but with different values. For example, this series of buttons allows you to choose one size for a pizza:

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> What size pizza?<P> <INPUT TYPE=RADIO NAME="pizzasize" VALUE="S">small<BR> <INPUT TYPE=RADIO NAME="pizzasize" VALUE="M">medium<BR> <INPUT TYPE=RADIO NAME="pizzasize" VALUE="L">large<P> <INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

What size pizza?

small

medium

large

submit

Page 30: Forms Tutorial

Note that it is the content of the VALUE attribute that is sent to the CGI, not whatever text happens to appear next to the radio button.

If one of the items should be the default selection, use the CHECKED attribute:

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> What size pizza?<P> <INPUT TYPE=RADIO NAME="pizzasize" VALUE="S" >small<BR> <INPUT TYPE=RADIO NAME="pizzasize" VALUE="M" CHECKED >medium<BR> <INPUT TYPE=RADIO NAME="pizzasize" VALUE="L" >large<P> <INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

What size pizza?

small

medium

large

submit

If no CHECKED attribute is used, different browsers have different ways of displaying the initial state of a series of radio buttons. Netscape and MSIE have none of the buttons selected. Mosaic selects the first button.

TYPE = PASSWORD

PASSWORD indicates that the field is for typing in a password. PASSWORD works just like a TEXT type field, with the difference that whatever is typed is not displayed the screen (in case someone is watching over your shoulder or you have to leave the work station). Instead of showing what you typed in, the browser displays a series of asterisks (*), bullets (·), or something to show that you are typing, but not what you are typing. So, for example, this code:

<FORM ACTION="../cgi-bin/mycgi.pl" METHOD=POST> name: <INPUT TYPE=TEXT NAME="realname"><BR> password: <INPUT TYPE=PASSWORD NAME="mypassword"> <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

gives us this form:

name:

password:

submit

Note that PASSWORD fields are not sent encrypted, they are sent in the same manner as all the other elements on the form: in the

clear. Note also that when you use PASSWORD you should also set the form METHOD to POST.

TYPE = HIDDEN

HIDDEN indicates that the field is invisible and the user never interacts with it. The field is still sent to the CGI, and scripts can also

use the hidden field. HIDDEN is commonly used as output of a CGI which creates a new form for more input. For example, a web site which facilitates online discussions may use a hidden field to keep track of which message is being responded to:

<H2>Your Reply</H2> <FORM METHOD=POST ACTION="../cgi-bin/mycgi.pl"> <INPUT TYPE=HIDDEN NAME="postingID" value="98765"> name: <INPUT NAME="realname" SIZE=30><BR> email: <INPUT NAME="email"><BR> subject: <INPUT NAME="subject" VALUE="Re: Hamlet and hesitation" SIZE=30> <P> comments:<BR>

Page 31: Forms Tutorial

<TEXTAREA NAME="comments" COLS=50 ROWS=10 WRAP=VIRTUAL> Joe Smiley wrote: : I think Hamlet doesn't act because if he does, the play's over. </TEXTAREA> <P><INPUT TYPE=SUBMIT VALUE="Send It!"> </FORM>

which gives us

Your Reply

name:

email:

subject: Re: Hamlet and hesitation

comments:

Joe Smiley w rote:

: I think Hamlet doesn't act because if he does, the

play's over.

Send It!

TYPE = SUBMIT

SUBMIT creates the "Submit" button which sends the form in to the CGI. In its simplest form, you can use SUBMIT and no other

attributes for the <INPUT ...> tag:

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> name: <INPUT NAME="realname"><BR> email: <INPUT NAME="email"><P> <INPUT TYPE=SUBMIT> </FORM>

name:

email:

Submit Query

You can customize the text used for the button using the VALUE attribute:

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> name: <INPUT NAME="realname"><BR> email: <INPUT NAME="email"><P>

name:

email:

Page 32: Forms Tutorial

<INPUT TYPE=SUBMIT VALUE="Send It!"> </FORM>

Send It!

You may sometimes find that you want to have more than one submit button on a form. If you give each button the same name, but different values, the browser will indicate which submit button was pressed:

<FORM ACTION="../cgi-bin/mycgi.pl"> Go to the check-out page? <INPUT TYPE=SUBMIT NAME="checkout" VALUE="YES"> <INPUT TYPE=SUBMIT NAME="checkout" VALUE="NO"> </FORM>

which gives us

Go to the check-out page? YES NO

TYPE = RESET

RESET resets the form so that it is the way it was before anything was typed in:

<FORM ACTION="../cgi-bin/mycgi.pl"> <INPUT TYPE=TEXT> <INPUT TYPE=SUBMIT> <INPUT TYPE=RESET> </FORM>

which gives us:

Submit Query Reset

For a while it was the perception that all forms "had" to have a reset button, but designers have found that resets are more likely to detract from the form than add to it. Users don't usually need to reset their forms, and they are more likely to accidentally hit the reset button than they are to actually want to wipe out their work. Unless you have a specific reason to expect that users will need a reset button it's probably best to leave it out.

If you do choose to use have a reset button in your form, consider adding a check if the user actually wants to reset. You can do this by adding an onReset event handler to the <FORM ...> tag:

<FORM ACTION="../cgi-bin/mycgi.pl" onReset="return confirm('Do you really want to reset the form?')" > <INPUT TYPE=TEXT NAME="query"> <INPUT TYPE=SUBMIT> <INPUT TYPE=RESET> </FORM>

which creates this form:

Submit Query Reset

If you add the VALUE attribute to the tag then that value is used as the text for the button.

<FORM ACTION="../cgi-bin/mycgi.pl" onReset="return confirm('Do you really want to reset the form?')" > <INPUT TYPE=TEXT NAME="query">

Page 33: Forms Tutorial

<INPUT TYPE=SUBMIT> <INPUT TYPE=RESET VALUE="Start All Over"> </FORM>

which gives us:

Submit Query Start All Over

TYPE = BUTTON

BUTTON defines a button which causes a script to run. Use the onClick attribute to give the script command(s). BUTTON is used only with scripting. Browsers that don't understand scripts don't understand this type of input and usually render it as a text input field.

<FORM> <TABLE BORDER CELLPADDING=3> <TR> <TD><NOBR>radius: <INPUT NAME="Circle_radius" SIZE=4></NOBR></TD> <TD><INPUT TYPE=BUTTON OnClick="Circle_calc(this.form);" VALUE="calculate"></TD> <TD ALIGN=RIGHT BGCOLOR="#AACCFF"> <NOBR>circumference: <INPUT NAME="Circle_circumference" SIZE=9></NOBR><BR> <NOBR>area: <INPUT NAME="Circle_area" SIZE=9></NOBR></TD> </TR> </TABLE> </FORM>

gives us

radius:

circumference:

area:

TYPE = FILE

FILE is used for doing file uploads in a form. File uploads are a relatively new and still not well-standardized type of form input, but they show great promise once the bugs are ironed out. File uploads allow you to send an entire file from your computer to the web server as part of your form input.

<FORM METHOD=POST ENCTYPE="multipart/form-data" ACTION="../cgi-bin/mycgi.pl"> File to upload: <INPUT TYPE=FILE NAME="upfile"><BR> <INPUT TYPE=SUBMIT VALUE="Submit"> </FORM>

which gives us this form (please note that the CGI for this form is set to accept only very small files, so try sending something under 1K):

File to upload:

Submit

Configuring a form for file uploads requires setting two attributes in the <FORM ...> tags in addition to using <INPUT TYPE=FILE>:

POST and "multipart/form-data" (as in the example above). When the data is sent, the original file name (including the full path) of the file as it was on your computer is sent to the web server. The CGI, however, is free to save the file as anything it wants -- or to not save it at all.

For the time being, only use form-based file upload if you know that the users will have Netscape (for example in an intranet or if the form is just for one person that you know has Netscape) or MSIE 4.0 or later.

An often expressed wish with file uploads is to have a way of suggesting the file type being uploaded. Netscape, for example, when it gives you the file upload dialog box, inexplicably assumes you want to upload an HTML file. Unfortunately, there is no way to suggest a file type.

Page 34: Forms Tutorial

TYPE = IMAGE

IMAGE creates an image that is also a "submit" button. When the user clicks on the image, the form is submitted.

<FORM ACTION="../cgi-bin/mycgi.pl"> name: <INPUT NAME="realname"> <INPUT TYPE=IMAGE SRC="../graphics/sfsubmit.gif" HEIGHT=110 WIDTH=160 ALT="Send It In!" ALIGN=ABSMIDDLE > </FORM>

gives us

name:

Most of the attributes that work with <IMG ...> also work with image inputs. Most particularly, make sure you use the ALT attribute.

Web browsers generally put a border around the image to indicate that it is "clickable", something that irritates many web designers because it detracts from the picture. If you want to get rid of the border, use BORDER:

<FORM ACTION="../cgi-bin/mycgi.pl"> name: <INPUT NAME="realname"> <INPUT TYPE=IMAGE SRC="../graphics/sfsubmit.gif" ALIGN="ABSMIDDLE" HEIGHT=110 WIDTH=160 ALIGN="ABSMIDDLE" ALT="Send It In!" BORDER=0 > </FORM>

gives us

name:

However, make sure you provide some cue that the image is clickable. Some objections have been raised to getting rid of the border, because it gets rid of the "standard" cue that the image is clickable. However, image submit buttons have become quite common, and if the button is properly designed to look like a button and if it is situated where the submit button would usually be (at the end of the form), users will generally pick up that it is a button.

In addition to sending the form data, the web browser sends the x,y coordinate of where the user clicked. If the image input is not given a name then the browser sends the x and y coordinates as the "x" and "y" input fields.

If the input image does have a name, the x and y coordinates are sent using the format name.x and name.y. For example, when you click on the submit image in this form, the coordinates are sent as MySubmitImage.x and MySubmitImage.y. This feature can be used to check which image was clicked. For example, suppose you want to have an image for "Yes" and another for "No". If you

You may also want

to check out how to

create a rollover

submit image for a

form

Page 35: Forms Tutorial

name them "Yes" and "No" you can check if they clicked "Yes" by checking for the existence of the "Yes.x" field in the data that is sent. Try these buttons:

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> <INPUT TYPE=IMAGE SRC="../graphics/yes.gif" HEIGHT=38 WIDTH=62 ALT="Yes" BORDER=0 NAME="Yes" > <INPUT TYPE=IMAGE SRC="../graphics/no.gif" HEIGHT=38 WIDTH=61 ALT="No" BORDER=0 NAME="No" > </FORM>

Attribute for <INPUT ...> NAME

NAME assigns a name to the input field, and is required in most circumstances. In forms which use CGI, the name of the input field is sent to the CGI:

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> favorite color: <INPUT NAME="favecolor"> <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

favorite color:

submit

For radio buttons and submit buttons you can use the same name in more than one input to indicate different options. Notice in these examples that the names are the same but the values for each option change:

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> What size pizza?<P> <INPUT TYPE=RADIO NAME="pizzasize" VALUE="S">small<BR> <INPUT TYPE=RADIO NAME="pizzasize" VALUE="M">medium<BR> <INPUT TYPE=RADIO NAME="pizzasize" VALUE="L">large<P> <INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

What size pizza?

small

medium

large

submit

<FORM ACTION="../cgi-bin/mycgi.pl"> Go to the check-out page? <INPUT TYPE=SUBMIT NAME="checkout" VALUE="YES"> <INPUT TYPE=SUBMIT NAME="checkout" VALUE="NO"> </FORM>

Go to the check-out page? YES NO

Page 36: Forms Tutorial

Forms that use scripting also use NAME. The input object is in the elements collection of the form object, and can be referred to by its

name using dot notation. In this example, we use the this.form.email to refer to the email input field. This code requests an email address. If none is given, the form is not submitted.

<FORM ACTION="../cgi-bin/mycgi.pl" onSubmit="return (this.email.value != '')" > email: <INPUT NAME="email"> <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

which gives us

email:

submit

Attribute for <INPUT ...> VALUE

VALUE sets the value for the input field. VALUE sets the default values for text and password fields, sets the button text in submit, reset and plain buttons, sets the values of the choices in radio buttons, sets the permanent values of hidden fields, and has no effect on file, and image fields.

text and password fields

For these types of fields, VALUE sets the default value:

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> name: <INPUT TYPE=TEXT NAME="realname" VALUE="wisnesky"><BR> password: <INPUT TYPE=PASSWORD NAME="realname" VALUE="pacman"> <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

name: w isnesky

password:

submit

It's a bad idea to send a default password, because the password can be obtained by looking at the HTML code.

radio buttons

use different values among several inputs with the same NAME to indicate different options:

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> <INPUT TYPE=RADIO NAME="color" VALUE="red" >Red<BR> <INPUT TYPE=RADIO NAME="color" VALUE="green" >Green<BR> <INPUT TYPE=RADIO NAME="color" VALUE="blue" >Blue<BR> <INPUT TYPE=RADIO NAME="color" VALUE="purple" >Purple <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

Red

Green

Blue

Purple

submit

Page 37: Forms Tutorial

submit, reset, and plain buttons

The text in these types of buttons is set using VALUE.

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> <INPUT TYPE=BUTTON VALUE="My Plain Button" ><P> <INPUT TYPE=RESET VALUE="My Reset Button" ><P> <INPUT TYPE=SUBMIT VALUE="My Submit Button" > </FORM>

My Reset Button

My Submit Button

If you can use the NAME attribute with submit buttons to make them act similar to radio buttons:

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> Go to the check-out page? <BR> <INPUT TYPE=SUBMIT NAME="checkout" VALUE="YES"> <INPUT TYPE=SUBMIT NAME="checkout" VALUE="NO"> </FORM>

Go to the check-out page?

YES NO

See RADIO for more details.

checkboxes

VALUE does not effect the checked state of checkboxes. If you want a checkbox to default to on, use CHECKED. Instead,

VALUE sets the value that is sent to the server if the user checks that checkbox. For example, if you wanted the checkbox to

send yessireebob you could set the checkbox like this:

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> <INPUT TYPE=CHECKBOX NAME="join" VALUE="yessireebob"> yes, sign me up! <P><INPUT TYPE=SUBMIT VALUE="join"> </FORM>

yes, sign me up!

join

If the checkbox is not checked, no value of any kind is sent to the server. By default, checkboxes send on.

hidden fields

Hidden fields have no purpose unless they have a value (they also need a name).

this code produces this

<FORM ACTION="../cgi-bin/mycgi.pl"> <INPUT TYPE=HIDDEN NAME="threadID" VALUE="1295"> <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

submit

Page 38: Forms Tutorial

Attribute for <INPUT ...> SIZE = integer

SIZE sets how wide a text or password field should be. It has no effect on any other type of field.

<FORM ACTION="../cgi-bin/mycgi.pl"> age: <INPUT TYPE=TEXT NAME="age" SIZE=2 ><BR> first name: <INPUT TYPE=TEXT NAME="first" SIZE=10><BR> last name: <INPUT TYPE=TEXT NAME="last" SIZE=30><BR> cosmic plane of origin:<BR> <INPUT TYPE=TEXT NAME="plane" SIZE=70> <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

gives us these fields of various length:

age:

first name:

last name: cosmic plane of origin:

submit

SIZE does not set the maximum length of what can be typed in. Use MAXLENGTH for that. Avoid setting SIZE to a length of 1. Although 1 is technically a valid size, many browsers have a hard time rendering a field that short. Try a size of 2.

Attribute for <INPUT ...> MAXLENGTH = integer

MAXLENGTH sets the maximum number of characters for text or password fields.

<FORM ACTION="../cgi-bin/mycgi.pl"> account ID: <INPUT TYPE=TEXT NAME="accountID" MAXLENGTH=4><BR> password: <INPUT TYPE=PASSWORD NAME="password" MAXLENGTH=8> <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

gives us this form:

account ID:

password:

submit

Attribute for <INPUT ...> CHECKED

CHECKED indicates that a radio button or checkbox should be on when the form first loads.

this code produces this

Page 39: Forms Tutorial

<FORM ACTION="../cgi-bin/mycgi.pl"> <INPUT TYPE=CHECKBOX NAME="maillist" CHECKED>Yes! Put me on the list! <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

Yes! Put me on the list!

submit

<FORM ACTION="../cgi-bin/mycgi.pl"> What color would you like?<BR> <INPUT TYPE=RADIO NAME="color" VALUE="green" >Green<BR> <INPUT TYPE=RADIO NAME="color" VALUE="red" >Red<BR> <INPUT TYPE=RADIO NAME="color" VALUE="blue" CHECKED >Blue<BR> <INPUT TYPE=RADIO NAME="color" VALUE="brown" >Brown <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

What color would you like?

Green

Red

Blue

Brown

submit

Checkboxes are off by default. There is no default for which radio button is on when the form loads; most browsers have none on, some put the first one on.

Your Ad Here

Attribute for <INPUT ...> BORDER = integer

BORDER is used for image submit buttons. BORDER indicates if there should be a visible border around the image. BORDER only has an effect in Netscape. MSIE does not put any visible border around image submits.

By default, Netscape puts a border around image submit buttons. By setting BORDER to zero you remove that border:

<FORM ACTION="../cgi-bin/mycgi.pl" METHOD=POST> name: <INPUT NAME="realname"> <INPUT TYPE=IMAGE SRC="go2.gif" BORDER=0 HEIGHT=22 WIDTH=50 ALT="go!"> </FORM>

which gives us

name:

Attributes for <INPUT ...> SRC = "image URL" HEIGHT WIDTH ALT HSPACE = integer VSPACE = integer ALIGN = LEFT | RIGHT | TOP | TEXTTOP | MIDDLE | ABSMIDDLE | CENTER | BOTTOM | ABSBOTTOM | BASELINE LOWSRC = "URL"

Page 40: Forms Tutorial

When you use the image type of input, you can use many of the same attributes as with <IMG ...>, including:

• SRC: the URL of the image

• ALT: alternate text for those who do not display/see the picture. Netscape still does not support this attribute for <INPUT

...>, and MSIE only started doing so with the 4.0 release.

• LOWSRC: the small bandwidth image to load before the main big image. If your submit buttons are so big you need this

attribute, they are probably too big.

• WIDTH and HEIGHT: dimensions of the image.

• ALIGN: how surrounding text is aligned to the image (actually, the input image should generally be on its own line.

Remember that the image is really a submit button, so it probably needs to stand out like a submit button).

• VSPACE and HSPACE: how far surrounding text should be from the image.

• BORDER: size of the border around the image. (see <INPUT BORDER="...">)

Attributes for <INPUT ...> DISABLED READONLY

READONLY and DISABLED both remove the functionality of the input field, but to different degrees. READONLY locks the field: the user

cannot change the value. DISABLED does the same thing but takes it further: the user cannot use the field in any way, not to highlight the text for copying, not to select the checkbox, not to submit the form. In fact, a disabled field is not even sent if the form is submitted.

Currently only MSIE recognizes either of these attributes.

this code produces this

<INPUT NAME="realname" VALUE="Hi There" READONLY> Hi There GO

<INPUT NAME="realname" VALUE="Hi There" DISABLED> Hi There GO

It's important to understand that READONLY merely prevents the user from changing the value of the field, not from interacting with

the field. For many types of fields, READONLY is irrelevent because you don't normally change the value. In checkboxes, for example,

you can check them on or off (thus setting the CHECKED state) but you don't change the value of the field. DISABLED, however, actually prevents you from using the field. Notice in these examples that you can set the checkboxes even though they are "read only":

this code produces this

<INPUT NAME="mushrooms" TYPE=CHECKBOX READONLY>mushrooms<BR> <INPUT NAME="onions" TYPE=CHECKBOX READONLY>onions<BR> <INPUT NAME="peppers" TYPE=CHECKBOX READONLY>peppers

mushrooms

onions

peppers

<INPUT NAME="mushrooms" TYPE=CHECKBOX DISABLED>mushrooms<BR> <INPUT NAME="onions" TYPE=CHECKBOX DISABLED>onions<BR> <INPUT NAME="peppers" TYPE=CHECKBOX DISABLED>peppers

mushrooms

onions

peppers

Page 41: Forms Tutorial

Attribute for <INPUT ...> ACCESSKEY = "text string"

ACCESSKEY specifies a shortcut key to go directly to the input field. The key is pressed along with the ALT key. For button style fields, using the key is like pressing the button. So, in the form produced with this code:

<INPUT TYPE=SUBMIT ACCESSKEY="g" VALUE="Go!" >

You can submit the form by hitting ALT-g:

Go!

For text entry fields, the key takes the cursor to that field. So with this code:

color: <INPUT TYPE=INPUT NAME="color" ACCESSKEY="c" >

ALT-c takes you to the input field:

color:

Your Ad Here

Attribute for <INPUT ...> TABINDEX = integer

Usage Recommendation

use it, but don't rely on it

Please note: TABINDEX is supported by MSIE 4.x and higher and Netscape 6.

Normally, when the user tabs from field to field in a form (in a browser that allows tabbing, not all browsers do) the order is the order the fields appear in the HTML code.

However, sometimes you want the tab order to flow a little differently. In that case, you can number the fields using TABINDEX. The tabs then flow in order from lowest

TABINDEX to highest.

This code:

Page 42: Forms Tutorial

<FORM ACTION="../cgi-bin/mycgi.pl" METHOD=POST> <TABLE BORDER CELLPADDING=3 CELLSPACING=5 BGCOLOR="#FFFFCC"> <TR> <TD>name: <INPUT NAME="realname" TABINDEX=1></TD> <TD ROWSPAN=3>comments<BR> <TEXTAREA COLS=25 ROWS=5 TABINDEX=4></TEXTAREA></TD></TR> <TR> <TD>email: <INPUT NAME="email" TABINDEX=2></TD></TR> <TR> <TD>department: <SELECT NAME="dep" TABINDEX=3> <OPTION VALUE="">... <OPTION VALUE="mkt">Marketing <OPTION VALUE="fin">Finance <OPTION VALUE="dev">Development <OPTION VALUE="prd">Production</SELECT></TD></TR> </TABLE> </FORM>

produces this form:

name: comments

email:

department: ...

TABINDEX can also be used with <A ...>, <TEXTAREA ...>, <SELECT ...>, and <BUTTON ...>.

Attribute for <INPUT ...> LANGUAGE = "JavaScript" | "JavaScript1.1" | "JSCRIPT" | "VBScript" | "VBS" | other language

Usage Recommendation

Use it, but understand some of the strange problems associated with this attribute.

<INPUT LANGUAGE="..."> describes the scripting language (e.g. JavaScript or VBScript) to use for scripting events which take

place in this input. The idea behind this attribute is the same as <SCRIPT LANGUAGE="...">: it designates which scripting

language is being used. If the browser doesn't recognize the language, it shouldn't try to run the scripts in such events as onClick

or onChange. Unfortunately Netscape ignores <INPUT LANGUAGE="...">, and so attempts to run the event scripts. If the scripts are written in VBScript, you get errors. We suggest you only use VBScript in forms where only MSIE users will use the page, such as in a company intranet.

Even if you are using MSIE only, this attribute has anomalies. If you use <SCRIPT LANGUAGE=VBSCRIPT>, any <INPUT ...> element afterwards is assumed to also use VBScript. If you wish to use JavaScript, you must explicitly add the attribute "JavaScript". We suggest that this situation shouldn't arise anyway. Although technically allowed, mixing scripting languages on a

single page falls in the category of bad form. Use either all JavaScript or all VBScript. If you use VBScript, use "VBScript" in every <INPUT ...> tag. Even if MSIE assumes you are using VBScript, it's better not to rely on that sort of faulty behavior.

See also <SELECT LANGUAGE="..."> and <TEXTAREA LANGUAGE="..."> (which has even more problems).

Attribute for <INPUT ...> onClick = "script command(s)"

onClick gives the script to run when the user clicks on the input. onClick applies to buttons (submit, reset, and button), checkboxes, radio buttons, and form upload buttons.

Page 43: Forms Tutorial

onClick is mostly used with plain button type inputs:

<FORM> <TABLE BORDER CELLPADDING=3> <TR> <TD><NOBR>radius: <INPUT NAME="Circle_radius" SIZE=4></NOBR></TD> <TD><INPUT TYPE=BUTTON OnClick="Circle_calc(this.form);" VALUE="calculate"></TD> <TD ALIGN=RIGHT BGCOLOR="#AACCFF"> <NOBR>circumference: <INPUT NAME="Circle_circumference" SIZE=9></NOBR><BR> <NOBR>area: <INPUT NAME="Circle_area" SIZE=9></NOBR></TD> </TR> </TABLE> </FORM>

gives us the "calculate" button in this form:

radius:

circumference:

area:

onClick can return a value to possibly cancel the action the button would normally perform. For example, we can use onClick to double check if the user really wants to reset the form data. In this form, if you click on the reset button, you get a dialog box asking if you really want to cancel. If you choose "cancel", the form is not reset.

<INPUT TYPE=RESET onClick="return confirm('Are you sure you want to reset the form?')" >

gives us

name:

email:

submit Reset

onClick is the only event handler for checkboxes and radio buttons. For example, this pizza ordering form has an "everything" option. When "everything" is selected, all the options for toppings go on and stay on, even if they are clicked. We do this by using onClick to call a function which checks if "everything" is on:

<SCRIPT TYPE="text/javascript"> <!-- function checkAll(pizzaForm) { if(pizzaForm.everything.checked) { pizzaForm.mushrooms.checked = true; pizzaForm.onions.checked = true; pizzaForm.greenpeppers.checked = true; pizzaForm.tomatoes.checked = true; } } //--> </SCRIPT> <FORM ACTION="../cgi-bin/mycgi.pl"> <INPUT TYPE=CHECKBOX NAME="everything" onClick="checkAll(this.form)">everything<P> <INPUT TYPE=CHECKBOX NAME="mushrooms" onClick="checkAll(this.form)">mushrooms<BR> <INPUT TYPE=CHECKBOX NAME="onions" onClick="checkAll(this.form)">onions<BR> <INPUT TYPE=CHECKBOX NAME="greenpeppers" onClick="checkAll(this.form)">green peppers<BR>

Page 44: Forms Tutorial

<INPUT TYPE=CHECKBOX NAME="tomatoes" onClick="checkAll(this.form)">tomatoes <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

which gives us

everything

mushrooms

onions

green peppers

tomatoes

submit

Attribute for <INPUT ...> onChange = "script command(s)"

onChange specifies script code to run when the data in the input field changes. onChange applies to input fields which accept text,

namely text and password fields. (<TEXTAREA ...> and <SELECT ...> fields also use onChange.)

The onChange event is triggered when the contents of the field changes. For example, when the user enters an email address in this form, a script does some basic validity checking on the value entered:

<SCRIPT TYPE="text/javascript"> <!-- function checkEmail(email) { if(email.length > 0) { if (email.indexOf(' ') >= 0) alert("email addresses cannot have spaces in them"); else if (email.indexOf('@') == -1) alert("a valid email address must have an @ in it"); } } //--> </SCRIPT> <FORM ACTION="../cgi-bin/mycgi.pl" METHOD=POST> name: <INPUT NAME="realname"><BR> email: <INPUT NAME="email" onChange="checkEmail(this.value)"><BR> destination: <INPUT NAME="desination"> </FORM>

which gives us this form:

name:

email:

destination:

Because onChange only occurs when the value changes, the user is only warned once about a bad value. That's generally the most

desirable way to do error checking. Even if the value is wrong, most users prefer to be warned just once.

The onChange happens whenever anything changes the value of the field, not just when the user enters a value. If a field's

Page 45: Forms Tutorial

onChange changes the value of the field, it's easy to get an endless loop. In situations like this, be sure to check if the change needs to happen. For example, this product order form makes sure that the "total" field is always the correct total (even if the user changes it). The subtotal field "vn_stVis" uses onChange to check if it is different than the hidden subtotal field "vn_stHold". If there is a

difference, vn_stVis is reset, which then causes another onChange event. However, that second time around the two fields are the same, and the script ends.

<SCRIPT TYPE="text/javascript"> <!-- function orderTotal(oform, prefix) { // set references to fields var qty = oform[prefix + "_qty"]; var stHold = oform[prefix + "_stHold"]; var price = oform[prefix + "_price"]; var stVis = oform[prefix + "_stVis"]; // only bother if the field has contents if (qty == "")return; // if the with is not a number (NaN) // or is zero or less // everything goes blank if(isNaN(qty.value) || (qty.value <= 0)) { qty.value = ""; stHold.value = ""; } // else the field is a valid number, so calculate the // total order cost and put that value in the // hidden subtotal field else stHold.value = (Math.round(qty.value * price.value * 100))/100; // call the routine which checks if the // visible subtotal is correct visTotal(oform, prefix); } // checks if the visible subtotal is correct // ie, if it equals the hidden subtotal field function visTotal(oform, prefix) { var stHold = oform[prefix + "_stHold"]; var stVis = oform[prefix + "_stVis"]; if (stVis.value != stHold.value) stVis.value = stHold.value; } // --> </SCRIPT> <FORM ACTION="../cgi-bin/mycgi.pl"> <TABLE BORDER CELLPADDING=3> <!-- table titles --> <TR BGCOLOR="#99CCFF"> <TH>item</TD> <TH>quantity</TD> <TH>price</TD> <TH>total</TD> </TR> <!-- v-neck sweater --> <TR BGCOLOR="#FFFFCC"> <TD>v-neck sweater</TD> <TD><INPUT TYPE=TEXT NAME="vn_qty" SIZE=3 onChange="orderTotal(this.form, 'vn')" ></TD>

Page 46: Forms Tutorial

<TD><INPUT TYPE=HIDDEN NAME="vn_price" VALUE="33.95">$33.95</TD> <TD ALIGN=RIGHT> <INPUT TYPE=HIDDEN NAME="vn_stHold"> <INPUT TYPE=TEXT NAME="vn_stVis" SIZE=10 onChange="visTotal(this.form, 'vn')" ></TD> </TR> <!-- JoAnn style blazer --> <TR BGCOLOR="#FFFFCC"> <TD>JoAnn style blazer</TD> <TD><INPUT TYPE=TEXT NAME="ja_qty" SIZE=3 onChange="orderTotal(this.form, 'ja')" ></TD> <TD><INPUT TYPE=HIDDEN NAME="ja_price" VALUE="99.95">$99.95</TD> <TD ALIGN=RIGHT> <INPUT TYPE=HIDDEN NAME="ja_stHold"> <INPUT TYPE=TEXT NAME="ja_stVis" SIZE=10 onChange="visTotal(this.form, 'ja')" ></TD> </TR> </TABLE> <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

which gives us this form:

item quantity price total

v-neck sweater $33.95

JoAnn style blazer $99.95

submit

Attributes for <INPUT ...> onFocus = "script command(s)" onBlur = "script command(s)"

Usage Recommendation

use it, but don't rely on it

onFocus is the event handler for when the input field gets the focus. onBlur is the event handler for when the input field loses the focus. The "focus" indicates which object in the window reacts to keyboard input. If a text field has the focus, then if you type something in the keyboard, the letters appear in that field. Focus shifts from one object to another usually by clicking on them with the mouse or by hitting the tab key.

Page 47: Forms Tutorial

A common use for onFocus and onBlur is to put a prompt message in the status bar of the browser window. Before we show how this is done, we'd like to suggest that you not do this. Fooling around with the status bar is a classic way to annoy your readers. People tend to rely on the status bar to know what's going on, and it's irritating to find usual information gone.

That being said, in the interest of completeness here's an example of onFocus and onBlur used to change the status bar. Notice that we use onFocus to give the message we want, and onBlur to change back to the default.

<FORM ACTION="../cgi-bin/mycgi.pl" METHOD=POST> name: <INPUT NAME="realname" onFocus = "window.status='Enter your name'" onBlur = "window.status=window.defaultStatus" ><BR> email: <INPUT NAME="email" onFocus = "window.status='Enter your email address'" onBlur = "window.status=window.defaultStatus" > <P><INPUT TYPE=SUBMIT VALUE="submit"> </FORM>

gives us

name:

email:

submit

One final note about onFocus: don't use it to call an alert() box. Some browsers interpret the alert box as grabbing the focus, then

when the box closed, the focus goes back to the input field, which again runs the onFocus event opening the alert box, etc. This endless loop is not a good way to impress your readers.

Attribute for <INPUT ...> onKeyPress = "script command(s)"

Usage Recommendation

use it, but don't rely on it

<SCRIPT ...>

Page 48: Forms Tutorial

Usage Recommendation

use it, but don't rely on it

• TYPE: Which scripting language to use

• SRC: External source for script

• DEFER: Continue loading page while downloading script

• LANGUAGE: Deprecated indicator of language

• FOR: object for which this script is an event handler

• EVENT: the event this script handles

<SCRIPT ...> designates a script section of the page. The contents of <SCRIPT ...> are run using the scripting language set

by the rquired TYPE attribute. For example, the following <SCRIPT ...> sets a short JavaScript, by far the most common scripting language.

<SCRIPT TYPE="text/javascript"> <!-- document.write("right now: " + new Date()); //--> </SCRIPT>

which outputs the current date and time: right now: Thu Jul 17 01:42:14 UTC+0530 2008

It is a popular but inaccurate belief that the LANGUAGE attribute is required for <SCRIPT ...>. In fact, LANGUAGE has never been a required attribute and has not been the standard way to indicate scripting language for several years.

<SCRIPT ...> elements should always begin with <!-- on the first line. The last line should begin with the line-level comment

string for the scripting language (// in JavaScript) followed by -->, as in the example above.

Attribute for <SCRIPT ...> TYPE = "text/javascript" | "text/vbscript" | other scripting language

Usage Recommendation

use it

TYPE, which is required, indicates the scripting language to use for the <SCRIPT ...> element. The most common value for TYPE is

text/javascript, which indicates that the script is written in JavaScript. Other possible values are text/vbscript for VBScript (which only supported by MSIE) or text/tcl for Tcl (a great language but not well supported at all).

The following example creates a small JavaScript script that outputs the current time:

<SCRIPT TYPE="text/javascript"> <!-- document.write("<P>right now: " + new Date() + "<P>"); //--> </SCRIPT>

which gives us:

right now: Thu Jul 17 01:42:43 UTC+0530 2008

Attribute for <SCRIPT ...> SRC = "URL"

SRC sets an external source for the script. If SRC is set then the contents of the <SCRIPT ...> element are ignored. For example, the following code loads a script located in the file myscript.js:

Page 49: Forms Tutorial

<SCRIPT TYPE="text/javascript" SRC="myscript.js"></SCRIPT>

The script in myscript.js writes out the current date and time to the page:

right now: Thu Jul 17 01:43:26 UTC+0530 2008

SRC allows you to create script libraries that can be used in many pages in your web site. There were some problems with the use of

SRC for quite a while. The folks in Redmond were apparently drinking too much latte because MSIE failed to support SRC until version4, making for a heap of webmaster headaches. Fortunately the overwhelming majority of people have evolved to MSIE 4 or later so SRC is a reasonably stable attribute now.

Attribute for <SCRIPT ...> DEFER

Usage Recommendation

use it, but don't rely on it

By default, when you use <SCRIPT SRC="..."> to load an external script into the page, the browser halts processing the page until

the external script is retrieved and executed. DEFER tells the browser not to wait for the script to load before going ahead and processing the rest of the page. The browser will load the script in the background while continuing to process the page.

DEFER, which is currently only supported by MSIE 5, is useful for situations where the script does not write anything to the page (i.e. does not use document.write()). In those situations it is better to let the user see the page while the script is executing.

For example, the following code indicates that the page should load the delscript.js script, but should do so in the background. delscript.js takes at least ten seconds to load (it was designed that way to simulate a lengthy download).

this code produces this

<SCRIPT SRC="delscript.js" DEFER ></SCRIPT>

this page

Attribute for <SCRIPT ...> LANGUAGE = JAVASCRIPT | LIVESCRIPT | VBSCRIPT | other

Usage Recommendation

use <SCRIPT TYPE="..."> instead

LANGUAGE used to be the standard way to indicate which scripting language the script element uses. LANGUAGE has given way to the

TYPE attribute. Use TYPE instead.