Você está na página 1de 27

This chapter utilizes narrative,

examples, and hands-on exercises to


introduce programming concepts
and Web development skills.

A Balanced Introduction to Computer Science


David Reed ©Prentice Hall, 2004

Chapter 9: Event-Driven Programming

The Internet already has too many static pages. Why add yours to the list? To get noticed,
your page must be live, it must do something, or offer some service. What better way is
there to liven pages up yourself than to use JavaScript, writing a short script that runs in
the browser, right in front of the user? JavaScript puts all the elements in a web page —
and the web page itself! — under your control.
Steven Holzner
Essential JavaScript

When I can't handle events, I let them handle themselves.


Henry Ford

One feature of the World Wide Web that makes it so popular is its interactive nature. When you access a
Web page, you don't just view it—you interact with it. You click links and buttons to access other pages
or to make new windows appear, or you enter information and view responses based on your input. In
these and many other ways, Web pages respond to your actions. We refer to such Web pages as “event-
driven,” in that they react to user-initiated events such as mouse clicks or keyboard entries.

Programmers can use JavaScript code to specify the way in which Web pages handle various events.
Thus, you can now apply your JavaScript programming skills to writing event-driven Web pages. For
example, instead of prompting users to enter a list of grades, you can design a page in which users type
grades in boxes and then click a button to compute their course average. Although the same JavaScript
code can compute the average in either case, the event-driven page offers the user a more attractive and
easy-to-use interface.

In this chapter, you will begin using JavaScript as a tool for controlling event-driven Web pages. The
first section demonstrates the use of buttons to initiate actions. We then introduce text boxes and text

9.1
areas, HTML elements used to read in user input and display output. At the end of the chapter, you will
learn how to define events that cause different images to appear in a page. It is important to note that the
event-driven features introduced in this chapter are far from exhaustive. In fact, HTML provides
numerous additional elements (such as radio buttons, check boxes, and selections lists) and JavaScript
provides additional methods for controlling those elements. However, buttons, text boxes, and text areas
are the most-commonly used tools for building event-driven pages, and are sufficient in many situations.
As such, this book will focus exclusively on these page elements.

Initiating Actions via Buttons

An event-handler is an HTML element that can be programmed (using JavaScript) to respond to a user’s
actions. The simplest type of event handler that can appear in Web pages is a button. If you have spent
any time surfing the Web, you have no doubt run across buttons like the one shown in Figure 9.1.

Figure 9.1: An HTML button.

A button is an HTML element that you can embed in a Web page, just as you would an image or a
table. Unlike these static elements, however, buttons can be associated with JavaScript code that will
run only when the buttons are clicked. For example, the button in Figure 9.1 might be assigned
JavaScript statements that cause a new page or window to open. When a user clicks this button, the
associated code would execute, redirecting the user’s browser to the specified page. The following
represents a generalized button element:

<input type="button" value="BUTTON_LABEL" onClick="JAVASCRIPT_CODE" />

A button’s VALUE attribute specifies the text label that appears on the button. For example, the button
in Figure 9.1 has the following attribute assignment: value="Click here for free money!". The
ONCLICK attribute specifies the action that occurs when a user clicks the button. This attribute can be
assigned any JavaScript statement or sequence of statements, enclosed in quotes.

Buttons and Forms

Unlike HTML elements that can appear anywhere in a page, button elements must always be placed
inside form elements. A form is a grouping of buttons and other event-driven elements within a page,
delimited by the tags <form name="FORM_NAME"> and </form>. Commercial Web developers often
employ forms to collect user input that must be transmitted over the Internet, such as an online
purchaser’s credit-card details and mailing address. However, since this text will not utilize forms for
this purpose, we can think of them simply as necessary wrapping for buttons and other event-handlers.

9.2
In the Web page in Figure 9.2, a form named LuckyForm contains a button with the label "Click Here
for Lucky Number". Once this page has been loaded, clicking the button will call the DisplayNumber
function to pick a lucky number—specified as a random integer between 1 and 100—and display it in an
alert window (Figure 9.3).

1 <html>
2 <!-- lucky.html Dave Reed -->
3 <!-- This page displays a lucky number at the click of a button. -->
4 <!----------------------------------------------------------------->
5
6 <head>
7 <title> Dave's Lucky Number </title>
8 <script type="text/javascript"
9 src="http://www.creighton.edu/~csc107/random.js">
10 </script>
11 <script type="text/javascript">
12 function DisplayNumber()
13 // Results: displays random number in an alert window
14 {
15 var luckyNum;
16
17 luckyNum = RandomInt(1, 100);
18
19 alert("Your lucky number is: " + luckyNum);
20 }
21 </script>
22 </head>
23
24 <body>
25 <div style="text-align:center">
26 <h2>Lucky Dave's Gift To You</h2>
27
28 <p>Numbers rule our lives. If you would like the benefit of Lucky Dave's
29 amazing powers of prognostication, click on the button below to receive
30 your guaranteed lucky number for the day!</p>
31
32 <form name="LuckyForm">
33 <input type="button" value="Click Here for Lucky Number"
34 onClick="DisplayNumber();" />
35 </form>
36 </div>
37 </body>
38 </html>

Figure 9. 2: Simple Web page containing a button.

9.3
Figure 9. 3: lucky.html rendered in a Web browser.

EXERCISE 9.1: Enter the contents of lucky.html from Figure 9.2 into a new Web
page, then load the page in the browser to verify that it behaves as described.

Once you have done this, save a copy of the page under the name lotto.html and
modify it so that it predicts the winning combination for a PICK-4 lottery. You should
update the page’s text appropriately and modify the button so that its label reads "Click
for Today's PICK-4 Winner". The DisplayNumber function, instead of displaying a
single number, should select four random numbers from the range 0 to 9 and then display
them in an alert window, separated by dashes. Figure 9.4 depicts an example of an alert
window that contains a PICK-4 winning number.

Figure 9. 4: Sample of a PICK-4 alert window.

9.4
Input/Output via Text Boxes

A button provides a simple mechanism through which users can interact with a Web page. By clicking
the button, the user initiates some action. Although an alert window is sufficient for displaying a simple
message, most tasks require more elaborate types of user interaction, such as where the user enters
several inputs and then views the results of a computation. Fortunately, HTML provides another form
element, called a text box, that can be used to implement these more complex interactions. A text box,
as its name suggests, is a box that can contain text (words or phrases). Unlike an alert window or
prompt window, however, a text box is displayed within the page itself. When the user enters characters
in a text box, that input is directly accessible via JavaScript code; similarly, JavaScript statements can
assign text to text boxes. Thus, a text box can be used both to receive user input and to display the
results of computations within the page.

The following represents a generalized text box element:

<input type="text" name="TEXTBOX_NAME" size=NUM_CHARS value="INITIAL_TEXT" />

A text box’s NAME attribute specifies the name used to identify that box. The SIZE attribute defines the
size of the box, which is measured by the number of characters it can contain. The VALUE attribute (if
present) specifies the text that the text box initially contains. Like buttons, text boxes are form elements
and therefore must appear inside form tags.

As you contemplate the functionality of text boxes, it may help you to think of memory cells as an
analogy. Recall that every JavaScript variable is associated with a specific memory cell— each
reference to a variable accesses the value in its memory cell, and each assignment to the variable stores a
value in that same memory cell (overwriting any value that was previously saved there). As you will see
in the following sections, a text box stores a value that can be accessed and assigned in a similar manner.
The main difference between a variable and a text box is that the contents of a text box are visible in the
page, whereas the values of variable are hidden.

Text Boxes for Displaying Output

Using JavaScript code, programmers can display a message in a text box by encapsulating the message
as a string and assigning the string to the box’s VALUE attribute. When you assign a value to a text
box, you must specify the absolute name of the box; this is accomplished by typing the word
"document", followed by the name of the form containing the box, then the text box name (all separated
by periods). JavaScript requires the use of full, absolute names as a way of avoiding confusion, since a
page might contain multiple forms with text boxes of the same name. The following represents a
generalized assignment to a text box:

document.FORM_NAME.TEXTBOX_NAME.value = STRING_TO_BE_DISPLAYED;

For example, Figure 9.5 depicts a modified version of the lucky.html page, which uses a text box,
rather than a separate alert window, to display the lucky number. The text box, named number, is four

9.5
characters wide and initially appears blank (i.e., its initial contents consist of an empty string ""). When
the user clicks the button labeled "Click Here for Lucky Number", the DisplayNumber function is
called to pick a random number between 1 and 100, as in Figure 9.3. However, instead of displaying the
number in an alert window, the function displays the number in the text box via the assignment:
document.LuckyForm.number.value = luckyNum.

1 <html>
2 <!-- lucky1.html Dave Reed -->
3 <!-- This page displays a lucky number in a text box. -->
4 <!------------------------------------------------------>
5
6 <head>
7 <title> Fun with Forms </title>
8 <script type="text/javascript"
9 src="http://www.creighton.edu/~csc107/random.js">
10 </script>
11 <script type="text/javascript">
12 function DisplayNumber()
13 // Assumes: document.LuckyForm.number exists in the page
14 // Results: displays random number in the text box
15 {
16 var luckyNum;
17
18 luckyNum = RandomInt(1, 100);
19
20 document.LuckyForm.number.value = luckyNum;
21 }
22 </script>
23 </head>
24
25 <body>
26 <div style="text-align:center">
27 <h2>Lucky Dave's Gift To You</h2>
28
29 <p>Numbers rule our lives. If you would like the benefit of Lucky Dave's
30 amazing powers of prognostication, click on the button below to receive
31 your guaranteed lucky number for the day!</p>
32
33 <form name="LuckyForm">
34 <input type="button" value="Click Here for Lucky Number"
35 onClick="DisplayNumber();" />
36 <br /><br />
37 <hr /><br />
38 Your lucky number is: <input type="text" name="number" size=4 value="" />
39 </form>
40 </div>
41 </body>
42 </html>

Figure 9. 5: Web page that displays a number in a text box.

9.6
Figure 9. 6: lucky1.html rendered in a Web browser.

EXERCISE 9.2: Enter the revised lucky.html text from Figure 9.5 into a Web page,
then load the page in the browser to verify that it behaves as described.

Make similar modifications to your lotto.html page, causing it to display the winning
PICK-4 lottery numbers in a text box. This means that your DisplayWinner function
must generate the four random numbers, concatenate them so that they are separated by
hyphens, and assign the resulting string to a text box.

9.7
Common errors to avoid...

Although form elements such as buttons and text boxes must appear within
form tags, it is not necessary to separate each form element in its own form.
In most cases, you can enclose every form element in a page within a single
set of form tags. It is not an error to include multiple forms in a page, but this
practice can lead to unnecessary confusion, since you must be sure to
associate each element with its correct form name.

Like variables, form elements must have unique names so that they can be
identified. If you mistakenly use the same name to represent multiple form
elements, no error will occur. However, the name will be associated with the
last element that you defined, and all subsequent access statements will refer
to that element.

Text Boxes for Accessing Input

Whereas some text boxes are used to display output, others are employed to handle user input. When a
text box is intended to accept input, users can enter data by clicking the mouse pointer inside the box
and typing. JavaScript code then accesses the text box’s contents using the absolute name of the text box
(where FORM_NAME and TEXTBOX_NAME will vary for each text box):

document.FORM_NAME.TEXTBOX_NAME.value

For example, the Web page in Figure 9.7 is an event-driven version of the temperature conversion page
convert.html from Chapter 7. The page contains a text box named fahrBox, which accepts user input.
The user enters a Fahrenheit temperature in fahrBox and then clicks the button labeled "Convert to
Celsius". When the button is clicked, the Convert function accesses the value that the user entered and
computes the corresponding Celsius temperature. The result of the computation is then assigned to a
text box named celsiusBox, which displays the converted temperature in the page.

9.8
1 <html>
2 <!-- convert1.html Dave Reed -->
3 <!-- This page converts temperatures from Fahrenheit to Celsius. -->
4 <!----------------------------------------------------------------->
5 <head>
6 <title>Temperature Conversion Page</title>
7
8 <script type="text/javascript">
9 function FahrToCelsius(tempInFahr)
10 // Assumes: tempInFahr is a temperature in Fahrenheit
11 // Returns: the equivalent temperature in Celsius
12 {
13 return (5/9) * (tempInFahr - 32);
14 }
15
16 function Convert()
17 // Assumes: document.TempForm.fahrBox contains degrees Fahrenheit
18 // Results: assigns document.TempForm.celsiusBox the equiv. temperature
19 {
20 var tempF, tempC;
21
22 tempF = parseFloat(document.TempForm.fahrBox.value);
23 tempC = FahrToCelsius(tempF);
24
25 document.TempForm.celsiusBox.value = tempC;
26 }
27 </script>
28 </head>
29
30 <body>
31 <h2>Temperature Conversion Page</h2>
32 <hr /><br />
33 <form name="TempForm">
34 Enter a temperature in degrees Fahrenheit:
35 <input type="text" name="fahrBox" size=10 value="" />
36 <br /><br />
37 <input type="button" value="Convert to Celsius" onClick="Convert();" />
38 <br /><br />
39 Equivalent temperature in degrees Celsius:
40 <input type="text" name="celsiusBox" size=10 value="" />
41 </form>
42 </body>
43 </html>

Figure 9.7: Web page that uses text boxes for input and output.

9.9
Figure 9.8: convert1.html rendered in a Web browser.

Common errors to avoid...

Note that, in the example from Figure 9.7, we called the parseFloat function
before performing a computation on the text box’s contents. Like input
returned by the prompt function, a value read in from a text box is initially
represented as a string. Therefore, you must use parseFloat to explicitly
convert text box values before treating them as numbers.

In this example, forgetting to parseFloat the value from the text box would
not affect the behavior of the page, because applying the subtraction operator
would automatically convert the text box value to a number. However, in
cases where a text box value is added to another value, the browser would
interpret the '+' operator as specifying concatenation involving the string
value. To avoid problems such as this, you should always call parseFloat
whenever you plan to treat the value in a text box as a number.

9.10
EXERCISE 9.3: Enter the revised convert.html text from Figure 9.7 into a new Web
page, then load the page in the browser to verify that it behaves as described.

In EXERCISE 7.2 of Chapter 7, you expanded your temperature conversion page so that
it could convert in both directions. Make similar modifications to the page from Figure
9.7, using text boxes for input and output. The page should include your FahrToCelsius
and CelsiusToFahr functions, as well as two text boxes, one for Fahrenheit and one for
Celsius. If users enter a temperature in the Fahrenheit box and click a button labeled
"Fahr Æ Celsius", then the corresponding temperature should appear in the Celsius
box. Likewise, if they enter a temperature in the Celsius box and click the button labeled
"Fahr Å Celsius", the corresponding temperature should appear in the Fahrenheit box.
Your page should look similar to the one depicted in Figure 9.9.

Figure 9.9: Sample appearance of temperature conversion page.

9.11
Designer secrets...

It is important to recognize that the programming skills you learned in previous


chapters are applicable to developing event-driven pages. Most of the pages you
wrote involved the same basic steps: (1) obtain inputs from the user via prompts,
(2) perform some computation on those inputs, then (3) display the results using
write statements. You placed the code for carrying out these steps within
SCRIPT tags in the body of the page, and the browser executed the code when
the page loaded.

In an event-driven page, the interface between the user and the code is
different—the user enters inputs directly into text boxes, and code executes when
the user clicks a button. However, the underlying algorithm for solving problems
remains the same: (1) obtain inputs from the user by accessing text boxes, (2)
perform some computation on those inputs, then (3) display the results by
assigning to text boxes.

If you compare the code from Chapter 7’s convert.html page (Figure 7.2) with
the event-driven version in Figure 9.7, you will see that the two pages are very
similar. Although the event-driven page uses text boxes to handle input and
output, the function triggered by the button performs the same tasks that the code
from the BODY of the original page does.

EXERCISE 9.4: Reimplement your grades.html page from Chapter 5 (EXERCISE


5.6) using text boxes and a button. Your new page should include text boxes in which the
user can enter each individual grade (homework average, lab average, midterm, and final
exam), as well as a single button to compute the course average. When the user clicks the
button, the program should call a function to determine the average and display it in
another text box.

Hint: This page should look a lot like the convert.html page from Figure 9.7, except
that grades.html will contain four text boxes for inputs. Instead of converting a
specified temperature from Fahrenheit to Celsius, your button will trigger the calculation
of a weighted average. Once the function executes, the result will be displayed in a
separate text box.

9.12
Text Boxes for Handling Both Input and Output

It is not uncommon for a particular sequence of JavaScript statements to employ the same variable in
multiple ways. For example, a program might use a variable initially to store a user input, then later
assign the result of some computation to that same variable. If we extend our analogy of text boxes as
similar to variables, it follows that the same text box can be used both to obtain user input and to display
the result of a computation.

Consider, for example, the JavaScript function in Figure 9.10. Assuming a text box named number
appears in the page (inside a form named NumForm), this function will access the number in the text box,
multiply that number by two, and assign the result back to the box. Thus, every time the function is
called, the current value of the text box will be doubled. A user can enter any number in the text box,
then click the button repeatedly to update the value displayed in the box.

function DoubleIt()
// Assumes: document.NumForm.number contains a number
// Results: the number in the box is doubled
{
var num;

num = parseFloat(document.NumForm.number.value);

document.NumForm.number.value = 2 * num;
}
Figure 9.10: JavaScript function that doubles the contents of a text box.

EXERCISE 9.5: Create a Web page named double.html whose HEAD includes the
DoubleIt function. The page should contain a text box with an initial value of 1 and a
button labeled "Double It". When the user clicks the button, the DoubleIt function
should be called to double the contents of the text box.

If you start with a value of 1 in the text box, how many times must you click the button
before the displayed value exceeds 500? How many times to exceed 1000?

9.13
Input/Output via Text Areas

Although text boxes provide a convenient method of reading in and displaying values in Web pages, the
fact that text boxes can contain only one line of text often limits their usefulness. An alternative is a text
area, which is similar to a text box but can contain any number of text lines. The following represents a
generalized text area element:

<textarea name="TEXTAREA_NAME" rows=NUM_ROWS cols=NUM_COLS wrap="virtual">


INITIAL_TEXT
</textarea>

A text area’s NAME attribute specifies the name used to identify that area. The number of rows
(horizontal lines that can contain text) and columns (maximum characters per line) in the text area are
defined by the attributes ROWS and COLS, respectively. The attribute assignment wrap="virtual"
ensures that text will wrap from one line to the next as needed, instead of running off the edge of the text
area. The initial text that appears in the text area (if any) is enclosed between the <textarea> and
</textarea> tags.

The Web page in Figure 9.11 contains two text boxes, each 15 characters wide, and a text area
consisting of four rows of 40 characters. The page asks users to enter their first and last names in the
text boxes. Once a user enters the names and clicks the button, the program accesses the contents of the
text boxes and incorporates the names in a greeting, which displays in the text area. Note that there is
no text between the opening and closing TEXTAREA tags (line 37), so the text area initially appears
empty.

9.14
1 <html>
2 <!-- greetbox.html Dave Reed -->
3 <!-- This page displays a personalized greeting in a text area. -->
4 <!---------------------------------------------------------------->
5
6 <head>
7 <title> Long Greeting </title>
8 <script type="text/javascript">
9 function Greet()
10 // Assumes: document.NameForm.firstName and
11 // document.NameForm.lastName contain names
12 // Results: writes a message with those names in document.NameForm.message
13 {
14 var firstName, lastName, greeting;
15
16 firstName = document.AreaForm.firstName.value;
17 lastName = document.AreaForm.lastName.value;
18
19 greeting = "Hello " + firstName + " " + lastName +
20 ", or may I just call you " + firstName +
21 "? You wouldn't be related to the " + lastName +
22 "s of Park Avenue, would you?";
23
24 document.AreaForm.message.value = greeting;
25 }
26 </script>
27 </head>
28
29 <body>
30 <form name="NameForm">
31 Enter your first name: <input type="text" size=15 name="firstName" />
32 <br />
33 Enter your last name: <input type="text" size=15 name="lastName" />
34 <br /><br />
35 <input type="button" value="Click for Greeting" onClick="Greet();" />
36 <br /><br />
37 <textarea name="message" rows=4 cols=40 wrap="virtual"></textarea>
38 </form>
39 </body>
40 </html>

Figure 9. 11: Web page that uses a text area for output.

9.15
Figure 9. 12: greetbox.html rendered in a Web browser.

Common errors to avoid...

As we saw in Chapter 2, browsers interpret HTML tags as a page loads,


displaying the appropriate formatting and/or elements in the rendered page.
Since the contents of a text box or text area can be updated repeatedly after a
page loads, the browser does not process text contained in these elements.
Therefore, HTML tags cannot be used to format text in a text box or text area.
If you mistakenly include HTML tags in the contents of a text box or a text
area, the tags will be treated like any other sequence of characters and will be
displayed exactly as typed. If you enter extra spaces in the text, they also will
appear exactly as you typed them.

If you want to force a line break within a text area, you can include the
character sequence \n within the text. Inserting this special sequence causes
subsequent text to begin on a new line, producing the same effect that <br />
does in HTML. Similarly, you can include the character sequence \t for a
tab.

9.16
EXERCISE 9.6: Enter the greetbox.html text from Figure 9.11 into a new Web page,
then load the page in the browser to verify that it behaves as described.

Once you have done this, modify the page so that it acts as an event-driven version of
your story.html page from Chapter 4. The page should incorporate text boxes in which
the user can enter the story’s missing words, and each text box should be accompanied by
a label (such as color: or noun:) to identify the type of word expected. Include a button
that, when clicked, incorporates the user’s words into the story and displays the story in
the text area.

EXERCISE 9.7: Reimplement your Magic 8-Ball page, magic.html, from Chapter 7
(EXERCISE 7.9). The new version should contain a text area in which the user can enter
a question, as well as a button for submitting that question. When the user clicks the
button, the program should generate a random response (as before) and display this
response in a text box.

Note: This page is unique in that it completely ignores the input it receives from the user.
Of course, users may not realize this –some may think that the Magic 8-Ball has
considered their questions carefully before responding!

Dynamic Images

In Chapter 2, you learned how to insert images in Web pages using the IMG element. For example,
suppose that happy.gif is an image file containing a picture of a happy face. The following tag, when
embedded in a Web page, would cause the happy.gif image to appear in the page:

<img name="photo" src="happy.gif" alt="Happy Face" />

This chapter has already demonstrated that user-initiated events can cause the contents of text boxes and
text areas to change. However, you can also use events to access and modify IMG elements within a
Web page. This ability enables you to design a page that displays different images when the user clicks a
button or enters a value in a text box. In such cases, the event triggers JavaScript statements that assign a
new file to the IMG element’s SRC attribute. For example, if a Web page contained the IMG tag listed
above, the following assignment would replace happy.gif with an image stored in the file sad.gif:

document.images.photo.src = "sad.gif";

9.17
Note that this assignment to the IMG element is similar to earlier assignments to text boxes and text
areas. There are two notable distinctions, however. First, images do not need to be embedded in forms.
Instead, all images in a Web page are specified via the group name images, which appears in the
assignment immediately after the word document to identify the element as an image. Second, images
do not contain values in the way that text boxes and text areas do. Instead, an IMG element is associated
with a source file, so the assignment is made to the SRC attribute of the image (as opposed to a VALUE
attribute of a text box or text area).

The Web page in Figure 9.13 contains a single IMG element, which is initially assigned the source file
happy.gif (assumed to reside in the same directory as the page). When the user clicks the button
labeled "I feel sad", the source file assigned to the image is changed to sad.gif, which displays a
sad face. Likewise, when the user clicks the button labeled "I feel happy", the source is reset back to
happy.gif, which displays a happy face.

1 <html>
2 <!-- pics.html Dave Reed -->
3 <!-- This page allows the user to select from among two images. -->
4 <!---------------------------------------------------------------->
5
6 <head>
7 <title> Picture Fun </title>
8 <script type="text/javascript">
9 function ChangeImage(picFile)
10 // Assumes: picFile is the name of an image file
11 // Results: changes the source of pic to picFile
12 {
13 document.images.face.src = picFile;
14 }
15 </script>
16 </head>
17
18 <body>
19 <div style="text-align:center">
20 <h2>How do you feel today?</h2>
21
22 <img name="face" src="happy.gif" alt="face image" />
23 <br /><br />
24 <form name="PicForm">
25 <input type="button" value="I feel happy"
26 onClick="ChangeImage('happy.gif');" />
27 &nbsp;&nbsp;
28 <input type="button" value="I feel sad"
29 onClick="ChangeImage('sad.gif');" />
30 </form>
31 </div>
32 </body>
33 </html>

Figure 9. 13: Web page that demonstrate dynamic images.

9.18
Figure 9. 14: pics.html rendered in a Web browser.

Common errors to avoid...

If you are using an older version of Netscape Navigator (i.e., version 4.7 or
earlier), you might notice something odd when you load the previous
example. Early versions of the Netscape browser associate an IMG element
with specific dimensions when the page loads. Any subsequent assignment
will resize the new image to fit the old source’s dimensions, which may in
turn warp the image.

Internet Explorer and later versions of Netscape Navigator automatically


adjust the image dimensions to fit the new source.

9.19
EXERCISE 9.8: Enter the pics.html text from Figure 9.13 into a new Web page and
modify the page so that it contains at least three buttons. Each button should assign a
new file to the SRC attribute of the IMG. You may choose any images you wish, but
remember that you must either download the images to your local directory or list the
images’ full Web URLs. Make sure that the labels on the buttons accurately describe the
images they control.

EXERCISE 9.9: Create a Web page named newpics.html that is similar to pics.html,
but which contains only one button controlling the image. When a user clicks this button,
a function (with no inputs) should be called to randomly select from among several
images.

For example, the following JavaScript statement, when executed, would randomly choose
from among four image file names (happy.gif, sad.gif, scared.gif, and bored.gif)
and assign the chosen file name to the SRC attribute of an image named face:

document.images.face.src = RandomOneOf(["happy.gif", "sad.gif",


"scared.gif", "bored.gif"]);

Looking Ahead…

In this chapter, you were introduced to a new method of enabling user interaction in your Web pages.
By incorporating buttons, text boxes, and text areas, you were able to develop pages in which users
could enter information easily and control the occurrence of specific actions. Unlike the pages you
wrote in earlier chapters, this chapter’s pages reacted to events initiated by the user – instead of simply
viewing output from JavaScript code that executed when the page loaded, the user was able to control
when code executed by clicking buttons and changing text-box values. These capabilities enabled you
to create Web pages that not only look more professional, but also are easier to use. In subsequent
chapters, you will utilize this event-driven style of programming more extensively.

Before we move on to more advanced programming skills, however, Chapter 10 pauses at the text’s
midway point to reflect upon computer science as a discipline. In earlier chapters, you have learned
about the hardware and software components of computer systems, the history of computers and the
Internet, and the role of algorithms in solving problems. You have also learned fundamental
programming concepts as you developed interactive Web pages using JavaScript. The next chapter
provides a general overview of computer science, including the basic themes and approaches that unite
such disparate topics into a cohesive discipline.

9.20
Chapter Summary

• Many Web pages are event-driven, meaning that they react to user-initiated events such as
mouse clicks or keyboard entries. Programmers can use JavaScript code to specify the way in
which Web pages handle various events.
• A button is the simplest type of event handler that you can insert in a Web page. When a user
moves the mouse pointer over a button and clicks, this event triggers a specific action. The
following represents a generalized button element:

<input type="button" value="BUTTON_LABEL" onClick="JAVASCRIPT_CODE" />

• Buttons and other event-handlers must be enclosed in form elements, which are specified via the
tags <form name="FORM_NAME"> and </form>.
• A text box is a form element included in Web pages for accepting user input and displaying
output. The following represents a generalized text box element:

<input type="text" name="TEXTBOX_NAME" size=NUM_CHARS value="INITIAL_TEXT" />

• You can access the contents of a text box by using the text box’s full name:
document.FORM_NAME.TEXTBOX_NAME.value. Similarly, you can display a value in a text box
by assigning the value to that text box’s VALUE attribute, such as in the assignment:

document.EventForm.firstName.value = "Alan";

• Like the return value of a prompt function, the contents of a text box are read in as a string, but
can be converted to a number using parseFloat if desired.
• Whereas a text box is limited to a single line of text, a text area can contain any number of lines.
The following represents a generalized text area element:

<textarea name="TEXTAREA_NAME" rows=NUM_ROWS cols=NUM_COLS wrap="virtual">


INITIAL_TEXT
</textarea>

• Images—unlike buttons, text boxes, and text areas—do not have to be embedded in HTML
forms.
• An event can be used to access and modify the SRC attribute associated with an IMG element,
such as in the assignment:
document.images.pic.src="sad.gif";

9.21
Supplemental Material and Exercises

More Practice with Form Elements

The pages that you wrote using prompts and write statements, while functional, left much to be desired
in terms of user interaction. Users had to enter each new value via a separate prompt window and, after
inputting data, could not review or edit previous entries. By contrast, event-driven form elements such as
buttons, text boxes, and text areas enable you to develop simpler, more intuitive user interfaces. In the
following exercises, you will reimplement certain pages from previous programming exercises, adding
form elements to improve the pages’ ease-of-use.

EXERCISE 9.10: Reimplement your years.html page from Chapter 7 (EXERCISE


7.7) using buttons and text boxes. You should include a text box in which the user can
enter a number of years and a button labeled "Convert to Seconds". When the user
clicks the button, the number of years in the box should be converted to seconds and
displayed in a separate box in the page. Remember to accompany each text box with a
label that describes its purpose.

EXERCISE 9.11: Reimplement your pickem.html page from Chapter 7 (EXERCISE


7.8) using buttons and text boxes. Recall that this page tested a person's ESP by
generating a random number between one and four, then prompting the user to guess
which number had been picked. For this exercise, modify the page so that it contains
four buttons, labeled “1”, “2”, “3”, and “4”. The user should submit a guess by clicking
the appropriate button. Once the user has guessed, JavaScript code should generate the
random number and display it in a text box or text area.

EXERCISE 9.12: Modify your double.html page from this chapter (EXERCISE 9.5)
so that it includes three additional buttons, labeled "Halve", "Increment", and
"Decrement". When the "Halve" button is clicked, the number in the text box should be
divided by 2. Similarly, the "Increment" button should add 1 to the value in the box, and
"Decrement" should subtract 1 from the value.

Note: The page should contain only one text box, and all four buttons should perform
computations on the value in that box. You will probably want to define separate
functions to control each of the three new buttons.

9.22
EXERCISE 9.13: Write an interactive Web page named swap.html that contains two
text boxes and a button. When the user clicks the button, the contents of the two text
boxes should be swapped. The text boxes should appear on the same line, centered in the
page, and the button should be centered below. Appropriate labels should accompany all
elements.

The ONCHANGE Attribute

In most of the event-driven pages we have examined so far, users must trigger each event by clicking a
button. However, programmers can also define events to occur when a user changes the contents of a
text box. The text box element’s optional ONCHANGE attribute, which is similar to the ONCLICK
attribute for buttons, specifies JavaScript code that executes when a user enters a new value in a text box
and then clicks the mouse pointer outside the box. For example, the Web page in Figure 9.15 contains
two text boxes, named box1 and box2. The ONCHANGE attribute for each box is assigned code
specifying that the box’s contents are to be copied to the other box whenever a user alters the box’s
value. The effect produced by these two ONCHANGE events is that the two boxes always mirror each
other, no matter which is changed.

1
2 <html>
3 <!-- copybox.html Dave Reed -->
4 <!-- This page copies the contents of one text box to another when changed. -->
5 <!---------------------------------------------------------------------------->
6 <head>
7 <title> Click and Copy </title>
8 </head>
9
10 <body>
11 <h2>Click to copy either value</h2>
12
13 <form name="BoxForm">
14 <input type="text" name="box1" size=10 value=""
15 onChange="document.BoxForm.box2.value = document.BoxForm.box1.value;" />
16 &nbsp; <tt><----></tt> &nbsp;
17 <input type="text" name="box2" size=10 value=""
18 onChange="document.BoxForm.box1.value = document.BoxForm.box2.value;" />
19 </form>
20 </body>
21 </html>
22

Figure 9. 15: Web page that demonstrates the ONCHANGE attribute.

9.23
Figure 9. 16: copybox.html rendered in a Web browser.

EXERCISE 9.14: Enter the copybox.html text from Figure 9.15 into a new Web page,
then load the page in the browser to verify that it behaves as described.

EXERCISE 9.15: Modify your convert.html page (EXERCISE 7.2) so that a button
click is no longer required to initiate temperature conversions. Instead, each text box
should have an ONCHANGE attribute specifying the action to be taken when a user
inputs a number. When the user enters a number in the Fahrenheit box, that value should
be accessed, converted to Celsius, and displayed in the Celsius box. Entering a number in
the Celsius box should activate the opposite conversion. Thus, your new page should
provide the same functionality as the old version, but should eliminate the need for a
button to trigger the events.

EXERCISE 9.16: EXERCISE 7.15 involved extending the convert.html page to


enable various measurement conversions (e.g., inches <-> centimeters, feet <-> meters,
and miles <-> kilometers). If you previously completed this exercise, reimplement your
expanded convert.html using text boxes. Design the page so that it contains six text
boxes on three lines; the text boxes representing inches and centimeters should appear on
the first line, followed by feet and meters on the second, then miles and kilometers on the
third. When a user enters a measurement in one box, the value should be converted to its
equivalent in the other system and displayed in the corresponding box. For example, if
the user enters 2 in the box labeled "inches: ", then 5.08 should automatically appear in
the box labeled "centimeters: ". Likewise, entering 1 in the box labeled
"kilometers: " should cause 0.6213712 to display in the box labeled "miles: ".

9.24
The ONFOCUS Attribute

Another attribute associated with text boxes and text areas is the ONFOCUS attribute. Similar to the
ONCLICK and ONCHANGE attributes, ONFOCUS specifies code that executes as soon as the user
focuses attention on the text box or text area, either by clicking the mouse inside it or by using the tab
key.

The ONFOCUS attribute is especially useful when you want to designate a text box or text area for
output only. For example, suppose you wanted to create a Web page that computes sales tax on various
transactions. The page could allow users to enter a sales amount in a text box, click a button, and view
the total price including tax in another box. For security reasons, you would like to prohibit the user
from modifying the contents of the total sale box—only the JavaScript code that computes the tax
should be able to change the box’s value. To prevent users from inputting values in the total sale box,
you can specify an ONFOCUS attribute for the box. Any time a user clicks the text box, this event
would call the predefined JavaScript function blur, which disables the user’s ability to enter text in the
box. The Web page in Figure 9.17 demonstrates the ONFOCUS attribute and the blur function (line
28).

1 <html>
2 <!-- sales.html Dave Reed -->
3 <!-- This page computes sales tax and demonstrates blur. -->
4 <!--------------------------------------------------------->
5
6 <head>
7 <title> Sales Tax </title>
8
9 <script type="text/javascript">
10 function TotalSale()
11 // Assumes: document.TaxForm.total contains a sales amount
12 // Returns: document.TaxForm.total gets amount + 6% sales tax
13 {
14 var sales, total;
15
16 sales = parseFloat(document.TaxForm.sales.value);
17 total = sales * 1.06;
18 document.TaxForm.total.value = total;
19 }
20 </script>
21 </head>
22
23 <body>
24 <h2>Sales tax calculator</h2>
25 <form name="TaxForm">
26 Sales amount: $<input type="text" name="sales" size=10 value=0 />
27 <input type="button" value="Total with 6% tax -->" onClick="TotalSale();" />
28 <input type="text" name="total" size=10 value="" onFocus="blur();" />
29 </form>
30 </body>
31 </html>

Figure 9. 17: Web page that demonstrates the ONFOCUS attribute.

9.25
Figure 9.18: sales.html rendered in a Web browser.

EXERCISE 9.17: Enter the sales.html text from Figure 9.17 into a new Web page,
then load the page in the browser to verify that it behaves as described.

Once you have done this, modify the page so that users can control the sales-tax rate.
First, add a text box to the page that accepts a tax rate as input. Then, define the
TotalSale function so that, when a user clicks the button, JavaScript code accesses the
rate box’s value and uses it to compute the total sales amount.

EXERCISE 9.18: Modify your sales.html page so that fractional monetary values are
rounded up to the next cent. For example, the amount $21.1894 should be rounded up to
$21.19. Using the following steps, you can round up a number so that only two digits
appear to the right of the decimal place:

1. Multiply the number by 100 (e.g., 21.1894 Æ 2118.94).


2. Round the value up using the Math.ceil function (e.g., 2118.94 Æ 2119).
3. Divide the number by 100 (e.g., 2119 Æ 21.19).

Encapsulate this computation in a separate function, then redesign your page so that it
uses this function to round up the total sales amount.

9.26
Aligning Form Elements with Tables

The supplemental material for Chapter 2 described how tables could be used to align text within a page.
Programmers often employ tables in conjunction with text boxes to align boxes and their associated
labels. For example, suppose that you wanted a page to include two text boxes, each accompanied by a
label to its left. By default, the text boxes would immediately follow the labels, leading to a ragged
appearance (Figure 9.19).

First name: <input type="text" name="first" size=12 value="" />


<br />
Age: <input type="text" name="age" size=3 value="" />

Figure 9. 19: Default alignment of text boxes with labels.

By placing the form elements in a table and designating one column for labels and another for text
boxes, you can align the elements and improve their appearance (Figure 9.20).

<table>
<tr><td>First name:</td>
<td><input type="text" size=12 value="" /></td>
</tr>
<tr><td>Age:</td>
<td><input type="text" size=3 value="" /></td>
</tr>
</table>

Figure 9. 20: Aligning the text boxes using a table.

EXERCISE 9.19: Modify your grades.html page (EXERCISE 9.4) so that the labels
and text boxes for the student's grades align in columns.

EXERCISE 9.20: Modify your story.html page (EXERCISE 9.6) so that the labels
and text boxes for the user's words align in columns.

9.27

Você também pode gostar