1. BASIC INTERACTIVITY

Creating interactive Web pages requires a way to communicate with your users. You need both a way to obtain information from them as well as respond dynamically. There are three basic ways of getting input from visitors:

  • Forms
  • Prompts
  • Events

In this lesson, you focus on using JavaScript prompts to get user input on your pages.

2. USE PROMPTS FOR USER INPUT

JavaScript prompts are an easy way to get information from the user. You can guide the user to enter numbers or text in response to your prompt. The basic format of a prompt includes two items:

prompt (message, default value)

Prompt is a method of the window object . You could also write a prompt in this way:

window.prompt (message, default value)

but you don't need to. The browser already knows it's a method of the window object.

An object is an entity that has properties and functions (called methods ) -- for example, JavaScript includes a built-in string object. A function is simply a group of code statements that are treated as a whole. A method is a function associated with a particular object; for example, the string object has a toLowerCase() method that converts a string into lowercase. You'll learn more about functions later in this lesson. Properties are an attribute of an object; for example, the string object has a length property that specifies the number of characters in the string.

Figure 3-1 shows a prompt dialog box in Internet Explorer. If you enter a default value, as shown in the following code, it'll be automatically entered into the prompt dialog box and highlighted so the user can enter a new value.

var fname = prompt 
  ("Please enter your first name: ");

A prompt returns a string. This string can be saved in a variable, as shown in the code where the prompt response is saved in the variable fname . You can then use that variable to display the value in an alert box, on the Web page, or in a new window.

Figure 3-1: Prompt dialog box in Internet Explorer.
Figure 3-1: Prompt dialog box in Internet Explorer.

If you don't use a default value, use an empty string ( "" ). For example, you can ask a user to enter their first name, such as the following:

var fname = prompt 
("Please enter your first name: ","");

When the prompt displays, the response area will be blank.

If you don't use a default value or an empty string, Internet Explorer automatically enters a value of undefined in the prompt dialog box, as shown as Figure 3-2. It's highlighted, and the user can enter a new value -- but it still can be confusing to the inexperienced viewer.

Figure 3-2: Undefined value in prompt dialog box.
Figure 3-2: Undefined value in prompt dialog box.

A prompt dialog box is modal , meaning that further processing of the page stops until you respond in some way. You don't have to enter anything, but you have to click either the OK or Cancel button. The only other alternative is to close the browser window.

If you want several pieces of input from the user, an HTML form is much more efficient.

3. USER INPUT CONSIDERATIONS

Whenever you collect user input, you need to consider all the possibilities including what happens if a user doesn't enter anything. Even with a simple prompt to obtain a user's first name, there are at least three different possibilities for user input, such as the following:

  • The user enters a response, and clicks OK. The response is saved as a string.
  • The user doesn't enter anything; only clicks OK. The response is saved as an empty string.
  • The user enters a response, and then clicks Cancel. The response is saved as null, meaning a nonexistent value.

Remember that a prompt returns a string. If you want to do numerical calculations -- specifically addition -- with prompt data, you need to convert it from string data to numeric data; otherwise, JavaScript will concatenate the strings together rather than adding the numbers.

You can create variable responses to user input by setting up conditions, such as if and else. Conditions and loops are covered in Lesson 4.

4. RESPOND WITH ALERTS

Alerts are one way to respond to a user's input. For example, in the first name prompt example in the previous section, you can add an alert to display the user's name and a greeting, such as the following:

var fname = prompt 
("Please enter your first name: ","");
alert ("Hello, " + fname);

This displays the alert box shown in Figure 3-3. The string is in quotation marks ("Hello, "), but the variable name (fname) is used without quotes. This tells the browser to use the value contained in the variable, not the variable name.

An Image
Figure 3-3: Displaying user input in an alert box.

If you want to display the variable name, you could add quotes to the variable name so that it's treated as a string:

alert ("Hello, " + "fname");

As you may have noticed, the alert box is modal, similar to the prompt box. The user must click OK for page processing to continue.

Use alerts sparingly. It can be very irritating to the user to be forced to respond to multiple alerts.

5. USE MULTIPLE PROMPTS

You can use more than one prompt if you want to collect more than one response. For example, you might ask for the user's first name in the first prompt, and the last name in the second prompt, as in the following code:

var fname = prompt 
("Please enter your first name: ","");
var lname = prompt 
("Please enter your last name: ", "");
alert ("Hello, " + fname + " " + lname);

Notice that there is a space (" ") inserted between the first name and last name variables so that the first and last name aren't pushed together in the alert box display.

6. USE PROMPTS FOR NUMERIC INPUT

You can also use a prompt to obtain numbers from the user and then use those numbers to do a calculation. Remember -- a prompt returns a string value. If you want to add the numbers together, you need to convert them from strings to numeric data using the techniques discussed in Lesson 2.

For example, if you want to display a user's age, you would do the following:

var tyear = prompt 
("Please enter the four digit number for the 
current year: ", "");
var byear = prompt 
("Please enter the four digit number for the 
year you were born: ", "");
var age = tyear - byear;
alert ("You were born in " + byear+'\n'+ 
"You will be " + age + 
" on your birthday this year.");

7. USE ESCAPE CODES

Notice the \n in the alert message code in the preceding example. This is a JavaScript escape code that creates a new line in the output. All Web programming languages include escape codes so that special characters can be used. In JavaScript, escape codes are preceded by a backslash. This tells the JavaScript interpreter that you want the character(s) following the backslash to be treated in a special way.

JavaScript escape codes include the following:

  • \b: backspace
  • \n: new line
  • \": double quote
  • \': single quote

The escape codes for quotations are the ones you'll use most frequently. Because pairs of quotation marks (either double or single) are used to delineate the beginning and end of strings, you need some way to include quotation marks within strings without causing a premature end to the string. If you want, for example, to quote a word within a string, you would use the following:

alert ("Don't you want to do the \"right\" thing?");

8. RESPOND WITH DOCUMENT.WRITE

You can also choose to respond by writing something to the page, either as an alternative to an alert, or in addition to an alert, as in the following code:

var fname = prompt 
("Please enter your first name: ",'');
alert ("Hello, " + fname);
document.write ("Hello, " + fname);

Create a page to include this code:

<!DOCTYPE HTML PUBLIC 
"-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Prompt and Alert</title>
<meta http-equiv="Content-Type" 
content="text/html; charset=iso-8859-1">
<script type="text/javascript" language="JavaScript">
<!--
var fname = prompt 
("Please enter your first name: ", "");
alert ("Hello, " + fname);
document.write ("Hello, " + fname);
// -->
</script>
</head>
<body>
</body>
</html>

Notice that there's nothing in between the body tags, so nothing displays on the page until the document.write statement is read by the browser.

9. USE DOCTYPE STATEMENTS

The first line of code in the previous example

<!DOCTYPE HTML PUBLIC 
"-//W3C//DTD HTML 4.01 Transitional//EN">

is a DOCTYPE statement. A DOCTYPE tells the browser which version of HTML you're using in the page. You don't have to use a DOCTYPE statement, but it's definitely recommended for the following reasons:

  • A DOCTYPE helps the browser process your page, and display it in the way you intended.
  • To use the features of the DOM (Document Object Model) to create interactivity and to create dynamic combinations of CSS (Cascading Style Sheets) and JavaScript effects on your pages, your code must be Web-standards compliant. The DOM is discussed further in Lesson 6. Web standards are the specifications created by the W3C (World Wide Web Consortium) for HTML, CSS, XML (Extensible Markup Language), and many other languages.

A full discussion of Web standards isn't within the scope of this course, but for more information, take a look at:

You can use The W3C Validation Service to check your pages for Web-standard compliance.

10. USE FUNCTIONS

All Web programming languages, including, JavaScript, use functions. Functions are an efficient way to use and store blocks of code statements. JavaScript includes many built-in functions, such as prompt, and you can also create your own functions for code blocks that you want to reuse.

Function definitions are usually included in script blocks in the head section of a page -- other than JavaScript's built-in functions, a function must be defined before it can be used. Because the code in the head section is executed before the code in the body section, functions are usually defined in the head section and called (invoked) from the body section.

To create a function, you must define it and give it a name, such as the following

function myCat (catname) {
alert 
(catname + " is a great name for a cat!");
}

A function includes the following:

  • A name: myCat
  • Parameters: the variable(s) inside the parentheses that follow the function's name: catname
  • A code block between curly braces: { alert (catname + " is a great name for a cat!");}

The function definition is everything in between the opening and closing curly braces { }.Even if there are no parameters for a particular function, you must use the parentheses after the function name.

To invoke a function, use the function's name in a script statement, such as:

myCat("Fluffy");

In this case, you give the catname variable the value of "Fluffy" when you call the myCat function.

You can return a value from a function by using a return statement, such as:

function quatro (item) {
var IV;
IV = item * 4;
return IV;
}

Obviously, a function to multiply by 4 is not particularly useful, but this should illustrate the basic idea.

A function should always include a return statement, even if no value is being returned, such as:

function myCat (catname) {
alert (catname + " is a great name for a cat!");
return;
}

Moving On

In this lesson, you learned how to use a prompt to get input from users as well as how to display this information by using an alert box or writing the information directly to the Web page with a document.write statement. You also learned the basics of functions.

In the Lesson 4, you'll learn how to create conditions to respond in different ways to different input, and make loops to automate activities.

Before you move on, don't forget to do the assignment and take the quiz. In addition, visit the Message Board to check in with your fellow students.