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.
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.
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
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.
Open the file in the FireFox Web browser so you can reload and see the results after each step.
<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.
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.
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.
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.
<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?
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.
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.
<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.");
'
/>
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
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.
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.
<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.
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.
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?
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.
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.
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
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!
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
Time Zone |
Difference From Local Time |
|
|
|
|
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
So the algorithm for shifting time (ignoring am/pm for now), is something like this:
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).
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.