Computer Science building

Lab 2: Advanced HTML

Thu Sep 7 16:56:38 EDT 2023

Due September 24 at 11:59 PM

In Lab 1, you learned the basics of HTML. This week you get to experiment with three of its more advanced features: tables, forms, and Javascript. If you want to do serious web page design, you'll need to know a lot more than what's covered in these labs, primarily HTML and CSS for layout, and Javascript for dynamic behavior. Resources you might look at include W3schools.com for HTML, CSS and Javascript.

Homeless person will code for food

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.

As in Lab 1, you have to ensure that the HTML file that you are creating is a proper text file.


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>. The browser will count the number of rows and the number of columns in the longest row and make a table of the appropriate size. In the final table, every row will have as many columns as the longest 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 the 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. None are required; 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 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 80 pixels wide, and WIDTH=80% will result in a table that is 80% as wide as the browser window.
BGCOLOR 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="#ffdab9"). 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 (for instance, "red" is all red, no green, no blue, and "yellow" is red and green but no blue). 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 bright red is "#FF0000" (maximum red, no green, no blue) and bright yellow is "#FFFF00"; "#888800" is a dingy khaki. (The page rgbtxt.html gives 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 Controls 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 Controls 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 Controls the default background color of every cell in the row. As with the BGCOLOR attribute in the <TABLE> tag, BGCOLOR can 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 Controls the horizontal alignment in the text in the cell. Its default is LEFT, but you can set it to CENTER or RIGHT.
VALIGN Controls the vertical alignment in the text in the cell. Its default is MIDDLE, but you can set it to TOP or BOTTOM.
BGCOLOR Controls the background color of this cell. If no BGCOLOR is specified, the cell will have the same background color as the row.
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 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 SPA 207 SPA 207 SPA 207
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>SPA 207</TD>
	<TD>SPA 207</TD>
	<TD>SPA 207</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 lab2.html that you will soon upload so people can view it at https://your_netid.mycpanel.princeton.edu/lab2.html.

Be sure that your lab2.html file is proper HTML, including html, head, title, and body tags, all properly terminated. If it isn't, it might not work on some browsers.

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.


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, 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.

In this part of the lab, 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 FORMs 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 look like this:

   <FORM METHOD="post" 
      ACTION="https://bwk.mycpanel.princeton.edu/scgi-bin/mailform.cgi">
      <INPUT TYPE="hidden" NAME="email" VALUE="your_netid@princeton.edu">
   </FORM>
(with the entire ACTION tag on one line).

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. 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 someone selects "Dog" above and submits the form, the email would include "pet=Dog". If you don't name the 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 visitors type 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>. Include the NAME attribute with a descriptive name to help identify it later.

Next, type in whatever you want to appear inside the text area. Since text areas are primarily for collecting information, you don't need to put anything inside, but 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, close the text area </TEXTAREA>.

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, give your 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 often, but if you do, you may use any of the attributes of text fields. (The password is sent to the server 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="classes1" VALUE="mat103">
MAT 103 <BR>
<INPUT TYPE="checkbox" NAME="classes2" VALUE="eng201">
ENG 201<BR>
<INPUT TYPE="checkbox" NAME="classes3" VALUE="cos109">
COS 109<BR>
<INPUT TYPE="checkbox" NAME="classes4" VALUE="phi201">
PHI 201
Which classes have you taken:
MAT 103
ENG 201
COS 109
PHI 201

As with the earlier 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:

Reset buttons reset the values of every component in the same form (between matching <FORM> and </FORM> tags), not just one item.

The optional attribute VALUE sets 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 lab2.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. (The mail will come from princetonpersonal.reclaimhosting.com; OIT has outsourced management of the cpanel site.)

What you write in HTML

<TABLE BORDER=5 BGCOLOR="silver">
 <TR ALIGN=CENTER>
  <TD>
   <FORM METHOD="post" ACTION="https://bwk.mycpanel.princeton.edu/scgi-bin/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 programs 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 itself.

Javascript is part of the browser, so 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". As usual, W3Schools is a good place start; you might also try JSfiddle.net and Codecademy.

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 / Web Developer / Web Console brings up a debugging window that often helps identify the problem. Chrome and Safari have a similar feature. (Archie observes that Apple makes it hard to do this -- you usually have to dig around in Safari > Preferences > Advanced, then check the box saying "Show Develop menu in menu bar" in order to enable it.)

More advice: If you're not sure how to do something, keep in mind that the instructions that you are reading on this page contain the code necessary to do everything described. "Use the source, Luke!"

Javascript Events

Javascript is 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. This is done by attaching Javascript code 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.

One of the simplest Javascript commands, especially useful for debugging, is alert, which causes a popup window to appear with a message. As a simple example, you could add a button that causes an alert message to appear when clicked; here's what it might look like:

For the full impact, push the button. 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. Note that we have to use single quotes to surround the command(s), since double quotes enclose the alert message.

Other events include onLoad, which occurs when the page is initially loaded, and onBeforeUnload, which occurs just before the page is exited, for example when the user pushes the "Back" button. You can put onLoad in the BODY part, with a line like this:

   <BODY onLoad='alert("loading the page")'>

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

   <BODY onBeforeUnload='alert("bugging out")'>
and you can have both events in the BODY tag.
Note that onBeforeUnload behaves differently with different browsers. For some browsers, an exit box will pop up without your message in it. For others (Safari on the Mac and Internet Explorer on the PC seem to be in this category), your message will be part of the exit box.

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("https://www.princeton.edu")' as the action for the button. This creates a new window or tab, so you now have two open at the same time; each time you push the button you get a new window or tab. This example used a fixed URL but you could 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 https:// prefix, so we preloaded that into the text field. This was created with this input:
    <form> <input type=text name=url size=40 value="https://">
           <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="https://www.princeton.edu"'>
    </form>

There's lots more that you can do with Javascript, but this is enough to suggest what's possible.

What you should do to your page

Add these Javascript embellishments to your page:
  • An alert that says "Welcome to my web page" when the page is first loaded. (If you want to this to say something like "Welcome to John's web page", you will have to take care with the interior single quote; the sequence \x27 is one way to handle it.)
  • An alert that thanks visitors for filling out the form (even if they didn't) when the page is exited. You can try onBeforeUnload. This appears to work, but only if you disable popup blocking, and only on some browsers. So this part is definitely optional.]
  • 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

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

          https://your_netid.mycpanel.princeton.edu/lab2.html

    Check your page to make sure the tables and forms display properly and that the page is fully accessible -- ask a friend to go through the whole page.

    When you are sure that your page is displaying correctly, including all images and sound files, upload your lab2.html and any other files to Gradescope. That will tell us that you have finished the lab.