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.