Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

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:

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.

Example 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:

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.

11fig05.jpg

Figure 11.5 The dialog box example's output, including a prompt dialog box.

Share ThisShare This

Informit Network