Lab 10—Time Shift Lab: Using Conditionals

Introduction

Now that you know the basics of working with JavaScript, we'll work on a more complicated Web page that will give us a chance to see how Web forms and JavaScript programming can work together. In the process, we'll also get some practice with conditionals. We'll see how to use HTML to produce the graphical user interface (GUI) for a Web-based program, and we'll write JavaScript code to perform the computations the program requires. Also as part of this lab, we'll learn to use Mozilla's JavaScript Console to help debug our code.

This lab will progress as a series of exercises, each building on the previous exercise, to show you how to build a larger program. This approach is important to learn. By breaking the program into smaller, simpler blocks and testing each block before you move on, you will always build on a solid, tested foundation. In this lab, when the initial pieces come together they will form our basic Version 0. The next level of enhancement will be Version 1 and the final will be Version 2.

  1. Build the GUI HTML form and test it.
  2. Add JavaScript to the form elements and test it.
  3. Validate input and test it. This program has now reached Version 0.
  4. Step aside for a moment to learn how to debug your code.
  5. Return to the project to add more complex coding, which becomes Version 1.
  6. Add another layer of more complex coding, which becomes Version 2.

 

See how versions of programs are built? Keep these two processes in mind as you progress through this lab—starting simple and testing and version-building.

Objectives

  • Create a more complicated Web form with JavaScript behind it
  • Learn to create drop-down boxes and understand when to use them
  • Gain more familiarity with assignment statements
  • Gain familiarity with conditionals
  • Learn to debug your code with the JavaScript console

Exercise 1—How To Use JavaScript with Web Forms

In an earlier lab, we put a <script> section in an HTML file; opening that Web page

in a browser caused the code to run immediately. In this lab, we'll see how we can write

JavaScript code that doesn't run immediately when the page opened, but instead runs when the user clicks on a button, enters a value in a text box, or otherwise performs some action. Roughly speaking, we'll be using JavaScript  to tell the page how to react when the user interacts with different parts of the page.

 

We'll start with a few, smaller exercises, but at the end of this lab, you'll create a page that can take a time from your local time zone and show you what time it would be in another U.S. time zone. The example in figure 6-2.1 shows the Pacific time zone.

Text Box: Figure 6-2.1—Sample Time Zone

Let's start with learning how to place text boxes, drop-down lists, buttons, and other kinds of form elements on a Web page. Strictly speaking, this part of the lab is really more about HTML than about JavaScript. In general, form elements allow users to interact with Web pages beyond just clicking on links. They are the input mechanism for interactive Web pages designed using JavaScript or another scripting language.

 

HTML offers a wide variety of form elements, so we'll only cover a few of the more commonly used ones here: the text box, the button, and the drop-down list box.

 

  1. Start a new Web page file and save it as time_zones.html. Don't forget to include a <head> section with the page title "U.S. time zones," in anticipation of the completed page.

 

Open the file in the FireFox Web browser so you can reload and see the results after each step.

  1. Add a <form> section. In the <body> section, add a <form> section. In the opening tag, include the name attribute as shown below.

<form name=timeZones>

     </form>

At this point, nothing will appear in your browser, because the form itself is empty. Form elements must be placed inside a <form> section, rather than just mixed in with the rest of your HTML. We are also giving this form a name, timeZones. The reason for this will become clearer later, but we will use the form name in JavaScript code to access its form elements, e.g., to get whatever text the user has entered in a text box.

 

  1. Add an OK button to the form. Adding a button only requires a single <input> tag with a few attributes, as shown below. The value attribute is what sets the text appearing on the button. At this point, the button isn't set up to do anything, so clicking it will have no effect.
         <input type=button value="OK" />

 

  1. Add a text box to the form before the button. Text boxes are similarly simple, but we'll use a name attribute, which we'll use to get what the user entered from inside our JavaScript program.

Figure 6-2.2—Your Web Page 1

 

<input type=text name=hoursBox />

<input type=button value="OK" />

 

Your Web page should now look something like Figure 6-2.2.

 

  1. Add a value attribute with a value of 6 to the text box's input tag. Did this change the way your Web page appears when it is loaded?  If so, how?

 

  1. Text Box:   Time zone reference 
Not sure what time zone you live in? Want to know what time the U.S. government says it is in your town? Check out the Web site time.gov, which is run by the National Institute of Standards and Technology and the U.S. Naval Observatory. You can also find some interesting historical facts about timekeeping on their site.
Add explanatory text around the text box. It's good practice to provide the Web page user with some idea of what they're expected to do with the text boxes and other form elements.

 

Let's start building the user interface for our time_zone.html page. Add some text on either side of the text box's input tag so your page ends up as shown below. Use the time zone you actually live in.

 

  1. Text Box: Figure 6-2.3—Your Web Page 2
 

Resize the hoursBox text box. Since the user is only expected to enter at most two digits in the text box, we should make it a lot shorter. You can do this by adding a size attribute to the text box's input tag. Set the size to 2.

Exercise 2. How To Set Up JavaScript Behind the Form

We've seen how to set up a very simple form with a text box and a button, but at this point, nothing happens when the user enters something in the box or clicks the button. Generally speaking, so far, we've only described what the page looks like using HTML, but we haven't encoded what the page should actually do. For this, we need a scripting language like JavaScript.

 

In earlier labs, we saw how to add JavaScript code to your HTML so that the code is executed as soon as the page is loaded. While this is generally useful, this isn't what we're looking for here. In this part of the lab, we'll see how we can set up the form elements with short sections of code that run when the user interacts with them in some way (e.g., clicking). For instance, we'll start by "attaching" some code to the button we have on our page. To get warmed up, we'll just set up the button so that it pops up an alert dialog box when it is clicked, and doing this is about as simple as it sounds.

  1. Add an onclick attribute to the button's input tag as shown below. This code should look a little strange to you, since we're sticking a piece of JavaScript inside an HTML tag, but setting up the button this way will run the alert code each time the button is clicked.

     <input type=button value="OK"

           onclick='alert("OK clicked!");'

   />

 

Note: We've put the onclick line of JavaScript in single quotes. Why do you think it's necessary to use single quotes instead of double quotes in this case?

 

  1. Reload the page. Does anything different happen when the page is reloaded (but before click the button)? What happens when you click the button?

In general, you could put any amount of valid JavaScript code in the value of the onclick attribute.

 

Now that we've seen how to build a Web form and put JavaScript code behind it, we're ready to start on a "first draft" of the time_zone.html Web page in earnest.

Exercise 3—Version 0: How to Validate User Input

Even though the time_zone.html Web page might not seem too complicated to you, it's important to use an intelligent strategy for producing it. The recommended strategy for any programming task is to build up your project in small steps. Moving step-by-step will help ensure that you make steady progress (rather than get stuck and frustrated) toward a working solution. As we step through the process toward completion for the time_zone.html Web page, you'll see how this strategy works in more detail.

 

To begin, identify a reasonable, short-term goal: a simpler version of the final project that should be considerably easier to complete than the whole thing all at once. In the case of the time zone page, let's be very conservative and make our first goal a Web page that doesn't actually do any time zone computation. However, it will check what the user enters in the hoursBox text box to make sure the input is valid (i.e., make sure it makes sense). Input validation is frequently the first thing that programs do. After all, why bother proceeding with computation using the input if it doesn't make sense?

 

First, let's consider what we mean by valid input for this text box. Since we eventually plan to give the user the option of am or pm, we expect the user to enter an integer from 1 to 12. By using a conditional and some handy JavaScript tricks, we can check what the user enters in the text box and use alert to give the user instructions if they don't enter valid input. All of the code we write will be in the onclick value for the button. To get you started, we'll provide this code for you, but you'll be writing most of the remainder of the code for the time_zone.html Web page.

 

  1. Change the button's input tag as shown below. Note that we've changed the value attribute so the button says "Update" instead of "OK."

<input type=button value="Update"

     onclick='var hours = parseInt(document.timeZones.hoursBox.value);

          if (hours < 1 || hours > 12)
           {

           alert("Please enter an integer from 1 to 12.");

           return;

     }

     // using alert to display input as reality check

     alert("Input " + hours + " is valid.");

'

/>

 

  1. Reload the page and for each of the values listed below, try typing it in the text box and clicking the Update button. Report what happens for each of the values.

                        value: 10

                        value: 1

                        value: 16

                        value: -2.1

                        value: 11.53

                        value: 5hey

                        value: hey

You've already seen conditionals in your reading assignments, but the parseInt line probably looks a little mysterious to you. First, you should recognize that this line declares a variable called hours. What's being stored in this variable? Two things are happening on the right side of the assignment here (i.e., on the right side of the =). First, we're retrieving the value inside the hoursBox text box. Look inside the parentheses after parseInt, and you'll see how we're using the form name (timeZones) and the text box name (hoursBox) to get the value:

 

     document.timeZones.hoursBox.value

           

Reading from left to right, we're asking for the current HTML document's timeZones form's hoursBox form element's value. Kind of like an Internet hostname, this identifier goes from general to specific, with periods separating the parts of the name. (Now do you see why it was important to give the form and the text box name attributes?)

 

What does the parseInt do? parseInt is a handy JavaScript way of converting whatever the user enters in the text box into an integer value. For instance, if the user enters 11.53, JavaScript's parseInt will convert that to just 11, dropping the decimal part. If the user enters a number followed by some letters (e.g., 5hey), parseInt will drop off the letters and give us just 5. What parseInt doesn't do is make sure the number entered falls within a certain range, which is why we use the conditional to check it ourselves after the parseInt line.

 

The return that executes if the user's input is out of range simply causes the code to stop executing. In other words, return prevents the rest of the code from executing if the user's input was not valid. (Note that the second dialog box never appears if the input is out of range.)

 

We can extend the input validation even further with another built-in JavaScript trick, isNaN. NaN stands for "Not a Number," and it works hand-in-hand with parseInt. If the user's input doesn't even remotely resemble an integer (e.g., a bunch of letters or words), the parseInt line will store the special value NaN in the hours variable. In that case, it doesn't even make sense to try to compare it to 1 and 12 to check if it's in the valid range.

 

  1. Add the condition isNaN(hours) to the Boolean expression, making it the first of the three conditions that are checked. We'll leave it to you to decide whether you should use or (||) or and (&&) when adding this condition.

 

The user needs to provide two other pieces of input: whether the time is am or pm and the time zone for which the converted time is to be computed. These will be added in the form of drop-down lists, which are a little more complicated than text boxes and buttons to write in HTML. We'll provide the HTML for the am/pm list and leave the time zone list to you.

 

  1. Add the am/pm drop-down list by adding the HTML below to the timeZones form. Note that drop-down lists are added using a select section, rather than a single input tag. Inside the select section, you use single option tags for the individual selections to be included in the drop-down list.

<select name=ampmList>

   <option value="am">am

   <option value="pm">pm

</select>

 

Now you can use document.timeZones.ampmList.value to retrieve the current selection in this drop-down list.

 

  1. Replace the last alert line with the code below to test that your drop-down list is set up properly.

var ampm = document.timeZones.ampmList.value;

alert("Input " + hours + ":00 " + ampm + " is valid.");

 

Explain why validation of input for the am/pm drop-down list is not necessary, as was the case with the hours text box.

 

  1. Add a text box for the program's output, the computed time in the selected time zone. Make it about size 8 and name it shiftedTimeBox.

 

This text box will be used to display the result of shifting the time to the selected time zone. So far, we've only seen how we can retrieve the value in a text box, but you can also assign a value to a text box. Add the assignment below to the very end of your button onclick code.

 

document.timeZones.shiftedTimeBox.value = "not sure yet";

 

Eventually, we will add code to compute the shifted time and replace the right size of the assignment with the correct expression to output that.

 

What happens when you reload the page, enter a valid hour value, then click Update?

  1. Add a second drop-down list for time zone selection. Use the am/pm list HTML above as a model. Name this new list zoneList and provide the choices Hawaii, Alaska, Pacific, Mountain, Central, and Eastern, which are the major time zones covering the fifty states.

 

  1. Add code to retrieve the selected value from zoneList and store it in a variable named zone. Use the analogous code for the am/pm list above as a model. Your Web page should now look similar to Figure 6-2.4.

Text Box: Figure 6-2.4—Your Web Page 3

Although it doesn't compute the shifted time, it does perform input validation, which, as you saw, is no small task. Now we're ready to add the code to return the time. But before we do, let's find out how to debug our code.

Exercise 4—How To Debug Your Code

Hopefully, you haven't made any errors in your programming thus far, but chances are that you have. One helpful tool built into the Mozilla and Mozilla Firefox browsers is the JavaScript console, which allows you to test out JavaScript and displays any JavaScript errors that have occurred on your Web page.

  1. Open time_zones.html and Mozilla or Mozilla Firefox. If you're using Internet Explorer, close it. Open Firefox, one of the only two browsers that have JavaScript Console (the other is Mozilla). To open your file with Firefox, right-click on time_zones.html, select "Open with…" and open it with Firefox.
  2. Open JavaScript  Console. The JavaScript console is located in Tools>JavaScript Console for Firefox, and Tools>Web Development>JavaScript Console for Mozilla.

 

The JavaScript Console should be blank, as shown in Figure 6-2.5. If it is not, it either means you have an error on your page, there was an error on your page but you fixed it (the JavaScript console doesn't automatically erase old error messages) or that these are errors from another page that you opened in this browser (yes, even professionally designed Web pages have JavaScript errors sometimes). In any case, you can hit "clear" to clear it for now.

Figure 6-2.5—JavaScript Console

  1. Introduce an error into your code intentionally to see what happens. Let's say your error is that you misspelled hours as "ours." hours is your onclick event handler. Make the change (misspell hours to "ours") now. Do not change the spelling of hours anywhere else, only change that one instance of it. Save your page (CTRL-S).

a           Refresh the page by clicking the Reload button  or pressing F5.

b           Check the JavaScript console; it should still be empty.

c           Test your form. On your page, leave all the fields blank, and click the OK button. See if your form gives you validation errors. It shouldn't, because you've intentionally placed an error in your JavaScript .

d          Look for errors on JavaScript console. It should have one error saying "ours is not defined, as illustrated in Figure 6-2.6." This error means that you are asking the browser to do something with "ours" but the browser can't find anything named "ours." In our case, that's because there IS nothing named "ours" because the event we're looking for is called "hours."

Figure 6-2.6—JavaScript Console Displaying an Error

Often the Console will provide a line number as well. Check the line number and find the matching line in your code, look for the error and fix it. Here, the problem was obviously a misspelling. You may see other reasons for things being "not defined." You'll discover that for yourself as you practice more JavaScript.

 

Be sure to fix your error before you move on!

Exercise 5—Version 1: How To Return the Time: Ignoring am/pm

Our next goal is creating a Web page that does part of the time conversion: it will give the time in the selected time zone, but it won't say whether the shifted time is am or pm, which, as you'll see, is a little tricky to figure out.

 

Before we try to write code to solve the problem of shifting time to a different time zone, make sure you can do it yourself! After all, how can we expect to write precise instructions for a computer to do it if we're the slightest bit unclear on how to do it ourselves?

 

Start by figuring out what the time difference is between your local time zone and the other time zones. For instance, if you're in the Pacific time zone, the difference to the Eastern time zone is +3 hours, and the difference to Hawaii is –2 hours. Fill in the table below for your local time zone. The time zones are listed in order from east to west, and each one differs from the next by one hour.

Time Zone

Difference From Local Time

Hawaii

 

Alaska

 

Pacific

 

Mountain

 

Central

 

Eastern

 

 

This table simplifies computing shifted time. All you do is take the local time and add the difference. If the result is less than 1 or greater than 12, you need to do a little arithmetic to end up with a valid time, but that's all.

For example, 1:00 Pacific time is 11:00 Hawaii time, because the difference is –2 hours. To get this, we add –2 to 1, which yields –1. Since –1 is not a valid time, we correct it by adding 12, and we get 11.

So the algorithm for shifting time (ignoring am/pm for now), is something like this:

  1. Depending on the selected time zone, determine the difference from local time.
  2. Add this difference to the hour part of the local time.
  3. If the result is less than 1, add 12; on the other hand, if the result is greater than 12, subtract 12.

Which of these steps do you think will require a conditional?

Based on this planning, write the above algorithm in code. We suggest you use at least a couple additional variables: one to store the time difference, one to store the shifted time (in hours). At the end, display the shifted time in the text box shiftedTime. You might want to leave out Step 3 above and get the time-shifting computation without the correction working first. (Remember, small steps!)

Don't forget to test your page with a variety of times to verify that it's working properly. Especially once you get the correction (Step 3) working, test that it works for times that you know will require correction (as in the Pacific-to-Hawaii example above).

Exercise 6—Version 2: How To Return the Time with Correct AM/PM

Recognizing when you need to add or subtract 12 to correct a shifted time is easier than recognizing whether shifting the time changed it from am to pm or vice versa. In general, the am/pm must be "flipped" (am to pm or pm to am), when the time shifts forward past 11:00 or shifts backward past 12:00. Expressing this as a Boolean expression requires some careful thought.

So you can concentrate on this complicated Boolean expression, start by writing the code to "flip" the value of the ampm variable. Test that it works properly by including the value of ampm in the output in shiftedTimeBox.

The additional code you need to add for this final part of the lab will look like this, leaving some blanks for you to fill in:

if ( Boolean expression ) {

     code to flip ampm

}

That's not a lot of code, but it will require some thinking.

Extra Credit

  • Try producing a slightly different version of the time_zone.html page that doesn't use am/pm but instead inputs and outputs time in 24-hour format (also known as "military time"). You can either start from scratch or make a copy of your current time_zone.html page and modify that.
  • Add more time zones from around the world.