Lab 3: Advanced HTML

Mon Oct 8 21:29:39 EDT 2007

By the end of this lab, you will be able to:

In Lab 2, you learned the basics of HTML. This week you get to experiment with three of the more advanced features: tables, forms, and Javascript. Once you've mastered this week's topics, it will be easier for you to create fancier web pages.

Part 1: Tables
Part 2: Forms
Part 3: Javascript
Part 4: Submitting your work

In this lab, we will highlight instructions for what you have to submit in a yellow box like this one.


Part 1: Tables

Basically, tables are boxes, divided into rows and columns, that help you organize and display content on your web page. If the information you want to display is too complicated for a list, or you can't get a group of pictures to align properly, a well-designed table may be the solution.

Here's a table with two rows and three columns
Column 1 Column 2 Column 3

After we cover the basic tags, we'll show some of the options that let you customize your tables.

Here is one of the most basic tables you can create:

1 2 3
4 5 6
7 8 9

It doesn't look much like a table, since it doesn't have borders, headings, or shading, but it is a good place to start since it doesn't require any extra attributes or tags.

Here's the HTML code that created it:

<TABLE>
<TR> <TD>1</TD> <TD>2</TD> <TD>3</TD> </TR>
<TR> <TD>4</TD> <TD>5</TD> <TD>6</TD> </TR>
<TR> <TD>7</TD> <TD>8</TD> <TD>9</TD> </TR>
</TABLE>

Each number is surrounded by <TD></TD> ("table data"). This creates a cell. Every three of these cells are surrounded by <TR></TR> ("table row"). This creates a row. The whole thing is surrounded by <TABLE></TABLE>. That's all it takes. The browser will count the number of rows and the number of columns in the largest row and make a table of the appropriate size. In the final table, every row will have as many columns as the largest row regardless of how many you typed in. Unspecified cells will be blank.

The <TABLE> tag

Every table must be surrounded by the <TABLE> and </TABLE> tags. Whenever your browser encounters a table, it reads in everything between these two tags before deciding how to arrange and display it. If you forget either one of them, your table will not show up at all!

The <TABLE> tag has quite a few attributes. You never need to include any of them, but here are a few of the more useful ones:

Attribute Description
BORDER Tables, by default, have no visible borders. If you would like your table to have a border, assign a value (in pixels) to this attribute. BORDER=1 (or just BORDER) will give your table a very thin border. BORDER=5 is much thicker.
CELLSPACING This attribute controls how much space (in pixels) there is between cells. Default cellspacing is 1, but you can use this attribute to raise or lower it (e.g., CELLSPACING=0).
CELLPADDING Cellpadding is the space between a cell's borders and its content. In tables with borders, you may want to set CELLPADDING=5 to avoid having text touch the edges of the cells.
WIDTH WIDTH can be assigned either a number of pixels or a percentage of the width of the window. For example, WIDTH=80 will result in a table that is always 80 pixels wide, and WIDTH=80% will result in a table that is always 80% as wide as the browser window.
BGCOLOR The BGCOLOR attribute controls the default background color of every cell in your table. As with the BGCOLOR attribute in the <BODY> tag, BGCOLOR can be assigned a built-in color or an RGB value (e.g., BGCOLOR="blue"). If no BGCOLOR is specified, the table will have the same background color as the page.

A note on RGB colors

Each color on a computer display is produced as a combination of the primary colors red, green, and blue, always referred to as "RGB". Some combinations have names ("red" is all red, no green, no blue, and "yellow" is red and green but no blue, for instance). But most combinations have no name; for those, you must specify the amounts of R and G and B yourself. This is done with three 2-digit hexadecimal numbers (numbers that range from 00 to FF), written as "#rrggbb". Thus red is "#FF0000" (maximum red, no green, no blue) and yellow is "#FFFF00"; "#888800" is a dingy khaki. (Here are a couple of web sites rgb1 and rgb2 that show a large number of comparatively standardized color names; some browsers recognize these names.)

The <TR> tag

Every row you create within your table must be surrounded by <TR> and </TR> tags. Here are some of the attributes you can include:

Attribute Description
ALIGN This attribute will control the horizontal alignment in the text of each cell in that row. Its default is LEFT, but you can set it to CENTER or RIGHT.
VALIGN This attribute will control the vertical alignment in the text of each cell in that row. Its default is MIDDLE, but you can set it to TOP or BOTTOM.
BGCOLOR The BGCOLOR attribute controls the default background color of every cell in the row. As with the BGCOLOR attribute in the <TABLE> tag, BGCOLOR can only be assigned a built-in color or RGB value (e.g., BGCOLOR="#FF00FF", which is red plus blue, or magenta). If no BGCOLOR is specified, the row will have the same background color as the table.

The <TD> tag

All text within your table should be surrounded by <TD> and </TD> (or <TH> and </TH>). These tags create the actual data cells, and thus have a lot of optional attributes to help you customize the cells:

Attribute Description
ALIGN This attribute will control the horizontal alignment in the text in the cell. Its default is LEFT, but you can set it to CENTER or RIGHT.
VALIGN This attribute will control the vertical alignment in the text in the cell. Its default is MIDDLE, but you can set it to TOP or BOTTOM.
BGCOLOR The BGCOLOR attribute controls the background color of this cell. As with the BGCOLOR attribute in the <TABLE> tag, BGCOLOR can only be assigned a built-in color or RGB value. If no BGCOLOR is specified, the cell will have the same background color as the row.
ROWSPAN

ROWSPAN controls how many rows the cell occupies, allowing you to merge the cells of more than one row into one tall cell. The default is 1, but you can raise this attribute to be anything up to the number of remaining rows. For example, ROWSPAN=3 will cause the cell to be 3 rows high.
When you have set a cell to occupy more than one row, you will usually be filling fewer cells in the next few rows. If, for example, you set ROWSPAN=4 on one cell in a table that is 5 columns wide, the next 3 rows would have 4 columns to fill instead of 5.

COLSPAN COLSPAN controls how many columns the cell occupies, allowing you to merge the cells of more than one column into one long cell. The default is 1, but you can raise this attribute to be anything (if you raise it above the number of remaining columns, it will create new ones on the right). For example, COLSPAN=3 will cause the cell to be 3 columns long.

Other table tags

There are two other tag pairs which can be used within tables:

Advanced Example

Here is a sample table created to display a schedule:

Schedule

Time Monday Tuesday Wednesday Thursday Friday
9:00 MAT 104 MAT 104 MAT 104
10:00 PHI 201 PHI 201
11:00 COS 109 COS 109 COS 109
Noon L U N C H

Notice that it uses many of the attributes we described above, especially ROWSPAN and COLSPAN. The HTML code that created this table is listed below. If you examine this code closely, you'll notice that the fourth row (11:00) seems to be missing a few cells. This is because the third row has two cells with ROWSPAN=2 which means they each automatically take up a cell in the fourth row as well.

HTML code for Schedule
<TABLE BORDER=1 CELLPADDING=5>

    <CAPTION><H3>Schedule</H3></CAPTION>

    <TR BGCOLOR=SILVER>
	<TH BGCOLOR=BEIGE>Time</TH>
	<TH>Monday</TH>
	<TH>Tuesday</TH>
	<TH>Wednesday</TH>
	<TH>Thursday</TH>
	<TH>Friday</TH>
    </TR>

    <TR ALIGN=CENTER VALIGN=MIDDLE>
	<TD BGCOLOR=BEIGE>9:00</TD>
	<TD>MAT 104</TD>
	<TD></TD>
	<TD>MAT 104</TD>
	<TD></TD>
	<TD>MAT 104</TD>
    </TR>
    <TR ALIGN=CENTER VALIGN=MIDDLE>
	<TD BGCOLOR=BEIGE>10:00</TD>
	<TD></TD>
	<TD ROWSPAN=2>PHI 201</TD>
	<TD></TD>
	<TD ROWSPAN=2>PHI 201</TD>
	<TD></TD>
    </TR>

    <TR ALIGN=CENTER VALIGN=MIDDLE>
	<TD BGCOLOR=BEIGE>11:00</TD>
	<TD>COS 109</TD>
	<TD>COS 109</TD>
	<TD>COS 109</TD>
    </TR>

    <TR ALIGN=CENTER VALIGN=MIDDLE>
	<TD BGCOLOR=BEIGE>Noon</TD>
	<TD COLSPAN=5 BGCOLOR=TURQUOISE>
	    L U N C H</TD>
    </TR>

</TABLE>

A table of your own...

For this part, you will have to create a table of anything that you like. It could be your own or some totally fake schedule, or anything else that you want. This table will be stored on a new web page called lab3.html in your public_html directory. You can view it at http://www.princeton.edu/~yourname/lab3.html.

Create a table with at least 4 rows and 4 columns (more is fine), at least 2 different colors, a link within, and at least one ROWSPAN or COLSPAN to merge adjacent identical cells.

Make sure that lab3.html accessible; check with one of the lab assistants or get a friend to look at it from his or her own browser. You may have to run the Unix command wwwpublic. Throughout the lab, be sure that your changes are being saved; you don't want to lose your work.


Part 2: Forms

Forms are basically collections of data entry fields like checkboxes, radio buttons, text boxes, etc., that ask for information from visitors to a page. When the visitor presses a "submit" button, all of that information is collected and sent to a web server, where it can be used by a program for some purpose. Search engines take keywords and generate lists of relevant pages. Guestbooks take entries and update a long HTML page. Comment forms usually send the comments to administrators via email. In fact, any time a web page asks you for information, it likely uses a form.

Today, you will create a form that collects information from the people who visit your web page and sends it to you via email. Later in the course, when you learn a bit more Javascript, you can experiment with writing code to process the data before mailing it.

Here's a sample form that shows all of the different form components you can use:
Text Field: Try typing in this password box:
Check out this checkbox:

RadioButton 1:
RadioButton 2:
RadioButton 3:

The <FORM> tag

Just as tables must be surrounded by <TABLE></TABLE>, everything in a form must go between <FORM> and </FORM>. There can be multiple FORM's in a page.

The <FORM> tag has two attributes that must be used if the form information is to be sent to a server:

Thus your form will begin with

<FORM METHOD="post" ACTION="http://www.cs.princeton.edu/~bwk/mailform.cgi">
<INPUT TYPE="hidden" NAME="email" VALUE="your_netid@princeton.edu">
(with the entire ACTION tag on one line) and end with
</FORM>

Adding components

Once you've opened your form, you can begin interspersing form elements with your HTML. All of the regular HTML tags will work, and you can also add text fields, text areas, select menus, checkboxes, radio buttons and more.

We're going to give a quick explanation of how to use each item and then ask you to create a form on your web page that lets visitors sign in and tell you about themselves.

Selection Boxes

Selection boxes let your visitors choose one option from a drop-down menu, like this:

Here is the HTML code that created it:

What you write in HTML How it looks on your web page
<SELECT NAME="pet">
<OPTION> Dog
<OPTION> Cat
<OPTION> Rock
<OPTION> No pets
</SELECT>

To begin, use the <SELECT> tag. Notice the NAME attribute inside it. It is very important to give every form component a name using the NAME attribute. Whenever someone submits your form, you will receive an email listing all of their answers. For example, if you selected "Dog" above and submitted the form, the email would include "pet=Dog". If you don't name your components, then you won't know which answer goes with which question!

Next, list all of the options. List each option on a separate line to make the HTML readable. Your selection box can have as many options as you wish, as long as each is preceded by the <OPTION> tag.

Finally, use the </SELECT> tag to close the selection box.

Text Areas

Text Areas let your visitors type in multiple lines of text, like this:

Here's the HTML code to create such a text area:

What you write in HTML How it looks on your web page
Questions/Comments:<BR>
<TEXTAREA NAME="comments">
I love this web site!
</TEXTAREA>
Questions/Comments:

To create the text area, use the tag <TEXTAREA> to open it. As usual, include the NAME attribute with a descriptive name to help identify it later.

Next, type in what you want to appear inside the text area. Since text areas are primarily for collecting information, you probably won't ever need to put anything inside and can omit that part. However, if you do want something to appear in the text area, note that each line of text you type appears on a separate line in the text area.

Finally, type </TEXTAREA> to close the text area.

The size of a text area can be set using the ROWS and COLS attributes to specify how many lines of text and how many characters per line should be displayed. For example, the original text area above can be made larger by using <TEXTAREA ROWS=4 COLS=30>

Text Fields

Text fields are one-line text boxes that are useful for collecting information like names, email addresses, phone numbers, etc. Here is an example, along with the code used to generate it:

What you write in HTML How it looks on your web page
Your name:
<INPUT TYPE="text" NAME="yourname" SIZE=20
   VALUE="type your name here">
Your name:

Text fields, along with the rest of the components we'll cover, use the <INPUT> tag. Since the same tag is used for buttons, checkboxes and other components, however, you need to specify a type in the TYPE attribute. For text fields, that type is "text".

As usual, we gave our component a descriptive name, but there are two other attributes you may also wish to set:

Password Fields

Password fields are just like text fields, except that, for security reasons, every letter you type into one displays as an asterisk. This prevents someone from looking over your shoulder and discovering your password as you type it. When the form is submitted, the actual text typed will show up in the email next to the NAME of the password field.

What you write in HTML How it looks on your web page
Secret Code:
<INPUT TYPE="password" NAME="secret" SIZE=5>
Secret Code:

Try typing in the password field above and notice the effect. You will probably not need to use this component very frequently, but if you do, you may use any of the attributes of text fields. (The password is sent totally in the clear, so this is at best a feeble protection mechanism.)

Checkboxes

Check boxes are exactly what they sound like -- little boxes which can be checked and unchecked by clicking on them. There are two different ways in which to use checkboxes in forms, however. The first example here is used for a group of unrelated questions:

What you write in HTML How it looks on your web page
I am a student:
<INPUT TYPE="checkbox" NAME="student">
<BR>
I drive a car:
<INPUT TYPE="checkbox" NAME="car" CHECKED>
I am a student:
I drive a car:

In this case, you want a separate answer for each checkbox question. Each has its own name and when the form is submitted, each will be listed only if it is checked. Notice that including the attribute CHECKED (without a value) in the second item's tag causes it to start out checked.

You can also use checkboxes to let visitors select more than one option from a list:

What you write in HTML How it looks on your web page
Which classes have you taken:<BR>
<INPUT TYPE="checkbox" NAME="classes" VALUE="mat103">
MAT 103 <BR>
<INPUT TYPE="checkbox" NAME="classes" VALUE="eng201">
ENG 201<BR>
<INPUT TYPE="checkbox" NAME="classes" VALUE="cos109">
COS 109<BR>
<INPUT TYPE="checkbox" NAME="classes" VALUE="phi201">
PHI 201
Which classes have you taken:
MAT 103
ENG 201
COS 109
PHI 201

In this case, the email submission would group all of these together under the name "classes". Instead of receiving a separate answer such as "mat103=on" for each of them, you would get something like "classes=mat103, phi201".

As with the above example, you can cause any of these to start out checked by including the CHECKED attribute.

Radio Buttons

Radio buttons are a lot like checkboxes, except that only one can be selected at a time. Just like station buttons on old radios, when you push one, the one that was pushed before pops out. Try out this example:

What you write in HTML How it looks on your web page
I like ice cream:<BR>
<INPUT TYPE="radio" NAME="ice cream" VALUE="lots">
A lot<BR>
<INPUT TYPE="radio" NAME="ice cream" VALUE="some">
Somewhat<BR>
<INPUT TYPE="radio" NAME="ice cream" VALUE="not">
Not at All
I like ice cream:
A lot
Somewhat
Not at All

A group of radio buttons must share the same name. In your email, you will get one answer for that name, which tells you which radio button was selected (e.g., "ice cream=lots" or "ice cream=some").

Reset Buttons

A Reset button, when pushed, resets all the answers in a form to their original default values. Usually, one reset button will be placed at the end of a form, right next to the submit button. Here is an example of a reset button in a small form (with only one other component).

What you write in HTML How it looks on your web page
Please enter a problem:<BR>
<INPUT TYPE="text" NAME="problem">
Press this button to make it go away:<BR>
<INPUT TYPE="reset" VALUE="Poof">
Please enter a problem:

Press this button to make it go away:

Don't be fooled by this example. Reset buttons will reset the values of every component in the same form (between matching <FORM> and </FORM> tags), not just one item.

The attribute VALUE is optional and will set the text message on the button. If you don't specify a VALUE, the button will usually just say "Reset".

Submit Buttons

The last component is the Submit button. It looks just like the Reset button, but instead of resetting all of the answers, it submits them. When a visitor presses the Submit button, all of the answers within the same form are collected and passed on to whatever program was specified in the ACTION attribute of the <FORM> tag.

Below is a Submit button with no other components. This one doesn't actually do anything, but we've provided this example so that you will know what it looks like and how to include one in your forms.

What you write in HTML How it looks on your web page
This is a Submit Button:<BR>
<INPUT TYPE="submit" VALUE="Submit Everything">
This is a Submit Button:

As with Reset buttons, the attribute VALUE is optional; if present, it sets the text message on the button. If you don't specify a VALUE, the button will usually just say "Submit".

Creating a Sign-in form for your web page

Now that you have learned how to use each component, we'd like you to combine them all by creating a Sign-in form for your web page. Basically, this is a form, like the one at the bottom of this page, that asks each visitor for a name, email address and other interesting information.

Create a sign-in form on your lab3.html page with at least 5 data entry fields (places to input answers), and using at least 3 different kinds of components. Before you start, check out the tips and example below, but please don't just copy the sample form we've provided.

Once you've finished your form, load the page and make sure it works: check your email to see if you receive the correct message.

While you work, keep the following in mind:

Here's a quick example to get you started. It uses a table to make a little sign-in form. Note carefully that it must contain your netid so that mail is sent to you.

What you write in HTML

<TABLE BORDER=5 BGCOLOR="silver">
 <TR ALIGN=CENTER>
  <TD>
   <FORM METHOD="post" ACTION="http://www.cs.princeton.edu/~bwk/mailform.cgi">
       <INPUT TYPE="hidden" NAME="email"  VALUE="your_netid@princeton.edu">
    <B>Your name:</B> 
    <INPUT TYPE="text" NAME="name"><BR><BR>
    <B>Your email:</B> 
    <INPUT TYPE="text" NAME="address"><BR><BR>
    <B>Please rate this page:</B><BR>
     <INPUT TYPE=radio NAME=rate VALUE=poor>     Poor
     <INPUT TYPE=radio NAME=rate VALUE=ok>     OK
     <INPUT TYPE=radio NAME=rate VALUE=good>     Good
    <BR><BR>
    <INPUT TYPE="submit">
    <INPUT TYPE="reset">
    </FORM>
   </TD>
  </TR>
</TABLE>
How it looks on your web page
Your name:

Your email:

Please rate this page:
Poor OK Good


Part 3: Javascript

Most web pages have more interesting and sophisticated behaviors than what you've done so far in this lab. Some pages won't let you submit a form until you've filled in required fields; some do actual computation, like the toy-machine simulator. Some cause new windows to appear on top of the original, or behind it, or off to the side (though sadly most such windows only display irritating advertisements). And sometimes trying to leave a web page causes a jump to a new web page, like a porn site, that you didn't want at all; there's no obvious way to get out.

Many of these effects are achieved by short programs ("scripts") that are written in a programming language called Javascript and included in the HTML text of a web page. In this section, we'll explore a small amount of Javascript so you can add some of these effects (preferably only desirable ones) to your web page. Learning this much Javascript will also be helpful when it comes to a couple of later labs that focus on Javascript.

Javascript is a simple language, and since it's part of the browser, you don't need to download any software or run any particular operating system to use it. There are many books and tutorials about Javascript if you want to pursue it further, or seek clarification of the sketchy descriptions here; Google for "javascript tutorial".

Advice: Programming languages are finicky about precise syntax, and if you make a mistake, your program may not do anything at all. If your Javascript isn't working, a syntax error might be the problem. As a partial solution, in Firefox, Tools / Javascript Console brings up a debugging window that might help identify some trivial syntax error.

The <SCRIPT> tag

Javascript in a web page is enclosed in <SCRIPT> ... </SCRIPT> tags that are analogous to other balanced tags like <B> ... </B>. Within this tag pair, you can write any amount of Javascript, ranging from a single line to many lines. Script tags can appear in many places within a web page; each one performs some action either when it is encountered as the page is loading, or when the commands within it are invoked by some event like the user pushing a button or moving the mouse to a particular region of the page, or when the page is exited.

One of the simplest Javascript commands, especially useful for debugging a broken script, is alert, which causes a popup window to appear with a message. If you put this sequence at the beginning of an HTML file, after <HEAD>, it will display a message when the page is loaded:

	<HEAD>
	<SCRIPT language="javascript">
		alert("we're about to load this page")
	</SCRIPT>
	...
You can put similar alert statements anywhere in a Javascript program to tell you how far the program has gotten or to display results of computations.

Events

Javascript is probably most often used to respond to user activity like pushing a button, pressing a key, reshaping a window or moving the mouse into or out of a window or some part of one. Javascript code can be attached to specific components of a web page so that when such a user "event" occurs for that component, the code runs and does whatever actions have been specified.

As a simple example, you could add a button that causes an alert message to appear; this is an unlikely task but it illustrates how the mechanism works. Here's what it might look like:

This was produced by this input:
	<form> <input type=button value="Hit me"
			onClick='alert("Ouch! That hurt.")'>
	</form>
The event onClick means "when the button is pushed"; it is followed by one or more Javascript commands surrounded by quotes. We use single quotes to surround the command(s), since double quotes enclose the alert message. (For the full impact, do push the button.)

Other events that you might use include onLoad, which occurs when the page is initially loaded, and onUnload, which occurs just before the page is exited, for example when the user pushes the "Back" button. onLoad occurs implicitly when the page is loaded, so you don't need to specify it directly; just add instructions to the <HEAD> part of the page, as we showed above.

onUnload is specified as part of the <BODY> tag, like this:

	<BODY onUnload='alert("bugging out")'>

You can open a new window by associating the command window.open(url) with an event like a button:

Here we used onClick=window.open("http://www.princeton.edu") as the action for the button. Notice that this creates a new window, so you now have two open at the same time; you can easily create more by pushing the button. And this uses a fixed URL but you could easily have both a button and a text field where your user can type the URL to be used, like this:

Note that the URL must include the http:// prefix, so we preloaded that into the text field. This was created with this input:
    <form> <input type=text name=url size=40 value="http://">
        <input type=button value="GO" onCLick='window.open(url.value)'>
    </form>

Properties

Notice especially how we used the value typed into the URL text field in the window.open command. The value is accessed as the value property of the text field called url. Every entity in the window, like the buttons and text areas and the page itself, has properties like name, color, size and text that can be used and even changed by Javascript code. For example the whole page has a property called bgColor that is normally set once and for all in the <BODY> tag. But you can change it dynamically with Javascript by setting document.bgColor to the desired color, like this:

The location property is the URL of the current web page. You can cause a new page to replace the current one, as if you had selected a link, merely by setting location to a new value:

    <form> <input type=button value="Princeton"
        onCLick='location="http://www.princeton.edu"'>
    </form>

There's lots more that you can do with Javascript, but this is enough to at least give a hint of what's possible.

What you should do to your page

Add these Javascript embellishments to your page:
  • An alert that says "Welcome to your name's web page" when the page is first loaded.
  • An alert that thanks visitors for filling out the form (even if they didn't) when the page is exited.
  • A button that says "Show my home page" and creates a new window with your home page when pushed.
  • At least two buttons that change the background color to shades that you like, and one that restores it to white. The colors must be expressed in RGB in hexadecimal, not as names.

  • Part 4: Submitting your work

    When you're done, send email to cos109@princeton.edu with the URL of the page that contains your schedule table and your sign-in form.

    The file containing the required work of the lab should be named lab3.html and should be saved in your public_html directory and thus accessible at

          http://www.princeton.edu/~yourname/lab3.html.

    Check all of your pages to make sure the tables and forms display properly and that the page is fully accessible.

    Be sure that any files you have created or altered are saved on your Unix account. If they were saved on the local hard disk (the C: drive or Desktop) then transfer them to your account by mapping your Network drive and saving them on it.