04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8: The Browser Object Model<br />

Alert dialogs are typically used when users must be made aware of something that they have no control<br />

over, such as an error. A user’s only choice is to dismiss the dialog after reading the message.<br />

The second type of dialog is invoked by calling confirm() . A confirm dialog looks similar to an alert<br />

dialog in that it displays a message to the user. The main difference between the two is the presence of a<br />

Cancel button along with the OK button, which allows the user to indicate if a given action should be<br />

taken. For example, confirm( “ Are you sure? ” ) displays the confirm dialog box shown in Figure 8 - 4 .<br />

Figure 8-4<br />

To determine if the user clicked OK or Cancel, the confirm() method returns a Boolean value: true if<br />

OK was clicked, or false if Cancel was clicked or the dialog box was closed by clicking the X in the<br />

corner. Typical usage of a confirm dialog looks like this:<br />

if (confirm(“Are you sure?”)) {<br />

alert(“I’m so glad you’re sure! “);<br />

} else {<br />

alert(“I’m sorry to hear you’re not sure. “);<br />

}<br />

In this example, the confirm dialog is displayed to the user in the first line, which is a condition of the if<br />

statement. If the user clicks OK, an alert is displayed saying, “ I ’ m so glad you ’ re sure! ” If, however, the<br />

Cancel button is clicked, an alert is displayed saying, “ I ’ m sorry to hear you ’ re not sure. ” This type of<br />

pattern is often employed when the user tries to delete something, such as an e-mail message.<br />

The final type of dialog is displayed by calling prompt() , which prompts the user for input. Along with<br />

OK and Cancel buttons, this dialog has a text box where the user may enter some data. The prompt()<br />

method accepts two arguments: the text to display to the user, and the default value for the text box<br />

(which can be an empty string). Calling prompt( “ What ’ s your name? ” , “ Michael “ ) results in the<br />

dialog box shown in Figure 8 - 5.<br />

Figure 8-5<br />

214

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!