Displaying Dialog Boxes
The window object includes three methods that are useful for displaying messages and interacting with the user. You've already used these in some of your scripts. Here's a summary:
-
The alert method displays an alert dialog box, shown in Figure 11.3. This dialog box simply gives the user a message.
-
The confirm method displays a confirmation dialog box. This displays a message and includes OK and Cancel buttons. This method returns true if OK is pressed and false if Cancel is pressed. A confirmation is displayed in Figure 11.4.
The prompt method displays a message and prompts the user for input. It returns the text entered by the user.
Figure 11.3. A JavaScript alert dialog box displays a message.
Figure 11.4. A JavaScript confirm dialog box asks for confirmation.
Creating a Script to Display Dialog Boxes
As a further illustration of these types of dialog boxes, Listing 11.4 shows an HTML document that uses buttons and event handlers to enable you to test dialog boxes.
Listing 11.4 An HTML document that uses JavaScript to display alerts, confirmations, and prompts
<html> <head><title>Alerts, Confirmations, and Prompts</title> </head> <body> <h1>Alerts, Confirmations, and Prompts</h1> <hr> Use the buttons below to test dialogs in JavaScript. <hr> <form NAME="winform"> <p><input TYPE="button" VALUE="Display an Alert" onClick="window.alert('This is a test alert.'); "></p> <p><input TYPE="button" VALUE="Display a Confirmation" onClick="temp = window.confirm('Would you like to confirm?'); window.status=(temp)?'confirm: true':'confirm: false'; "></p> <P><input TYPE="button" VALUE="Display a Prompt" onClick="var temp = window.prompt('Enter some Text:','This is the default value'); window.status=temp; "></p> </form> <br>Have fun! <hr> </body> </html>
This document displays three buttons, and each one uses an event handler to display one of the dialog boxes. Let's take a detailed look at each one:
The alert dialog box is displayed when you click on the first button.
The confirmation dialog box is displayed when you click the second button, and displays a message in the status line indicating whether true or false was returned. The returned value is stored in the temp variable.
The third button displays the prompt dialog box. Notice that the prompt method accepts a second parameter, which is used to set a default value for the entry. The value you enter is stored in the temp variable and displayed on the status line. Notice that if you press the Cancel button in the prompt dialog box, the null value is returned.
Figure 11.5 shows the script in Listing 11.4 in action. The prompt dialog box is currently displayed and shows the default value, and the status line still displays the result of a previous confirmation dialog box.
Figure 11.5. The dialog box example's output, including a prompt dialog box.