Hour 4. Getting Input and Displaying Output

Input and output are the cornerstones that enable programs to interact with the outside world. In the previous hour, you learned how important the output process is to programming because through output, your program displays information. A program must get some of its data and control from the user’s input, so learning how to get the user’s responses is critical as well.

The highlights of this hour include

Image Displaying output in JavaScript

Image Printing multiple occurrences per line

Image Separating output values

Image Using variables to hold information

Image Getting data in JavaScript

Image Prompting for data input

Image Sending output to your printer

Printing to the Screen with JavaScript

JavaScript has a variety of methods to display output to a web page. Which you choose will depend on your goal. Almost every program you write will output some data to the screen. Your users must be able to see results and read messages from the programs that they run.

There are several ways to output to the screen. One of the easiest way to print words on the website is to enclose them in quotation marks after a document.write statement. The following four statements embedded in an HTML document print names on the screen:

<script>
document.write("Sally Brown<br>");
document.write("John Wilson");
</script>

These statements produce the following output:

Sally Brown
John Wilson


Note

Keep in mind that in JavaScript, document.write is not always the best way to output text to the page. In fact, it has several limitations. But right now, you’re learning good generalized programming techniques, and it’s more about simple output that optimized output.


Remember that for any JavaScript statements, you need to bracket them with the <script> and </script> tags. You may also be wondering about the <br> tag at the end of the Sally Brown name. This signals to the browser to jump down to the next line, inserting a line break. Without it, your output would look like this:

Sally BrownJohn Wilson

The quotation marks are not printed—they mark the string to be printed. You may be wondering, “What if I wanted to print quotation marks?” JavaScript has an easy solution. If you enclose your string to be printed in single quote marks, you can then include the double quotation marks as something to print. For example, if you added the line

document.write('"what if I wanted to print quotation marks?"'),

The output would be

"what if I wanted to print quotation marks?"

Whether you use single or double quotation marks, understand that numbers and mathematical expressions will print as is inside the string. JavaScript will not do any math within a string. If you write

document.write("5 + 7");

JavaScript doesn’t print 12 (the result of 5 + 7). Because quotation marks enclose the expression, the expression prints exactly as it appears inside the quotation marks. The document.write statement produces this output:

5 + 7

If, however, you print an expression without the quotation marks, JavaScript prints the result of the calculated expression.

document.write(5 + 7);

does print 12.

Storing Data

As its definition implies, data processing means that your programs process data. That data must somehow be stored in memory while your program processes it. In JavaScript programs, as in most programming languages, you must store data in variables. You can think of a variable as if it were a box inside your computer holding a data value. The value might be a number, character, or string of characters.


Note

Actually, data is stored inside memory locations. Variables keep you from having to remember which memory locations hold your data. Instead of remembering a specific storage location (called an address), you only have to remember the name of the variables you create. The variable is like a box that holds data and the variable name is a label for that box so you’ll know what’s inside.


Your programs can have as many variables as you need. Variables have names associated with them. You don’t have to remember which internal memory location holds data; you can attach names to variables to make them easier to remember. For instance, Sales is much easier to remember than the 4,376th memory location.

You can use almost any name you want, provided that you follow these naming rules:

Image Variable names must begin with an alphabetic character such as a letter.

Image Variable names can be as long as you need them to be.

Image Uppercase and lowercase variable names differ; the name MyName and MYNAME are two different variables.

Image After the first alphabetic character, variable names can contain numbers and periods.


Caution

Avoid strange variable names. Try to name variables so that their names help describe the kind of data being stored. Balance04 is a much better variable name for an accountant’s 2004 balance value than X1y96a, although JavaScript doesn’t care which one you use.


Here are some examples of valid and invalid variable names:

Image

Caution

Don’t assign a variable the same name as a JavaScipt command or JavaScript will issue an invalid variable name error message.


Variables can hold numbers or character strings. A character string usually consists of one or more characters, such as a word, name, sentence, or address. JavaScript lets you hold numbers or strings in your variables.

Assigning Values

Many JavaScript program statements use variable names. Often, JavaScript programs often do little more than store values in variables, change variables, calculate with variables, and output variable values.

When you are ready to store a data value, you must name a variable to put it in. You must use an assignment statement to store values in your program variables. The assignment statement includes an equal sign (=) and an optional command var. Here are two sample assignment statements:

sales = 956.34

var rate = .28


Tip

The var keyword is optional and requires more typing if you use it. However, many other programming languages require that you use a keyword to first declare a variable, so it’s good programming practice to use the optional var keyword.


Think of the equal sign in an assignment statement as a left-pointing arrow. Whatever is on the right side of the equal sign is sent to the left side to be stored in the variable there. Figure 4.1 shows how the assignment statement works.

Image

FIGURE 4.1 The assignment statement stores values in variables.

If you want to store character string data in a variable, you must enclose the string inside quotation marks. Here is how you store the phrase “JavaScript programmer” in a variable named myJob:

myJob = "JavaScript programmer"   // Enclose strings in quotation marks

After you put values in variables, they stay there for the entire run of the program or until you put something else in them. A variable can hold only one value at a time. Therefore, the two statements

age = 67;
age = 27;

result in age holding 27, because that was the last value stored there. The variable age cannot hold both values.

You can also assign values of one variable to another and perform math on the numeric variables. Here is code that stores the result of a calculation in a variable and then uses that result in another calculation:

pi = 3.1416;
radius = 3;
area = pi * radius * radius;
halfArea = area / 2;

Getting Keyboard Data with Prompt

So far, the programs you’ve created have used specific pieces of information and data coded right into your programs. Even variables have been defined with specific values, such as the radius of the circle in Listing 4.1. While this is interesting, it’s ultimately limiting. To make programs more valuable, you need to get information from your user.

The prompt method is the opposite of alert. The prompt method receives values from the keyboard. You can then assign the values typed by the user to variables. In the previous section, you learned how to assign values to variables. You used the assignment statement because you knew the actual values. However, you often don’t know all the data values when you write your program.

Think of a medical reception program that tracks patients as they enter the doctor’s office. The programmer has no idea who will walk in next and so cannot assign patient names to variables. The patient names can be stored in variables only when the program is run.

When a program reaches a prompt call, it creates a dialog box that stays until the user types a value and presses the OK button. Here is a prompt:

prompt("What is your favorite color?");

When program execution reaches this statement, the computer displays a dialog box with the message you type in the quotation marks. The dialog box is a signal to the user that something is being asked and a response is desired. The more clear you make the statement you send to the prompt, the easier it will be for the user to enter the correct information.

Inputting Strings

Unlike many programming languages, a variable in JavaScript can hold either a number or a string. Any type of variable, numeric or string, can be entered by the user through a prompt dialog box. For example, this line waits for the user to enter a string value:

var fname = prompt("What is your first name");

When the user types the name in response to the question, the name is put into the fname variable.


Caution

If the user only presses OK, without entering a value in response to the prompt, JavaScript puts a value called null into the variable. A null value is a zero for numeric variables, or an empty string for string variables. An empty string—a string variable with nothing in it—is literally zero characters long.


Capturing Mouse Events

JavaScript does not just interact with the keyboard entries from users. In addition, there are methods of understanding when the user either clicks the mouse on a specific button or passes into a particular region. These types of actions are called events, and they will trigger and action if you have written code for something to happen when the events occur. For example, if the user clicks the mouse over a button on a web page form, the button’s onClick event is triggered only if you have written code for it.

A rollover effect can apply to buttons or text on the Web page. If text contains a rollover, the text can change color or change in another way when the user points to the text. Often, such rollover effect is used for menu selection. Figure 4.4 shows a web page with JavaScript-enabled text before the user moves the mouse pointer over one of the text items. Figure 4.5 shows how the Author Links text changes when the user moves the mouse pointer over the text. This rollover effect is possible only because the JavaScript that contains code to handle the rollover comes to the user’s computer inside the HTML web page. The code must run on the user’s computer to respond immediately to the mouse movement.

Image

FIGURE 4.4 A web page with JavaScript looks like any other until the user activates a JavaScript scriptlet.

Image

FIGURE 4.5 When the mouse pointer moves over text with a rollover effect, the JavaScript code changes the text’s appearance.

Summary

Proper input and output can mean the difference between a program that your users like to use and one they hate to use. If you properly label all input that you want so that you prompt your users through the input process, the user will have no questions about the proper format for your program. In addition to data entry, JavaScript provides methods that allow you to alter your website depending on the positioning of a visitor’s cursor position, adding another level of interactivity to your programs.

The next hour describes in detail how to use JavaScript to program calculations using variables and the mathematical operators, as well as some handy string-manipulation tricks.

Q&A

Q. What is the difference between an alert dialog box and a prompt dialog box?

A. Alert shares information with the website visitor, while a prompt asks the user to enter specific information.

Q. Why don’t I have to tell JavaScript what type of variable I want to use?

A. JavaScript is just that smart! Actually for most programming languages, you need to specify the type of variable, and if you try to put a different type of data in that variable, you can get an error or unpredictable results. JavaScript will change the variable type on the fly, so you can use the same variable as a string in the beginning of the program and then a number later. This is not the best idea, however. You should keep your variables focused on a specific type and a specific job.

Workshop

The quiz questions and exercises are provided for your further understanding.

Quiz

1. How do you print words in the output window?

2. How would you write an alert method that printed the sum of 10 and 20?

3. Declare a variable named movie and assign the last movie you saw in theaters to it.

4. True or false: You use the same code to jump down a line in both document.write and alert methods.

5. What is a variable?

6. How do you print the contents of variables?

7. What is a prompt?

8. Write a simple program that asks the user for their birthday in three separate prompts—one for month, one for date, and one for year, and then combine the three into a Month date, year format that you put up on the screen in an alert.

9. What do the onmouseover and onmouseout events do?

10. What does NaN stand for?

Answers

1. Use document.write to display words in an output window. If you want to create a dialog box with the displayed words, use the alert method.

2. alert(10 + 20);

3. (Obviously this should vary based on your most recent cinema-viewing experience.) For me:

var movie = "The Wolverine";

4. False. For document.write, you use the <br> code, and this would not work in an alert (you would print <br> to the screen. If you want to jump down a line, use the escape character “ ” (don’t feel bad if you got this wrong—we didn’t cover it yet).

5. A variable is a named storage location.

6. You can use either document.write or alert or a number of other methods to print the contents of a variable.

7. A prompt describes the information that a user is to type.

8. Here is one possible solution:

<!DOCTYPE html>
<html>
<body>

<h1>Birthday Bash</h1>

<script>

bYear = prompt("What year were you born?");
bMonth = prompt("What month were you born?");
bDay = prompt("What day were you born?");

bMessage = "You were born on " + bMonth + " " + bDay
              + ", " + bYear + "!";
alert(bMessage);

</script>

</body>
</html>

9. The onmouseover event will trigger some code when the user’s mouse pointer passes into a specific object (like an image, banner, or block of text). The onmouseout event will trigger some code when the user’s mouse pointer leaves that object.

10. NaN stands for “Not a Number.”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.72.74