Dialog Boxes
The Window object provides three methods for displaying simple
dialog boxes to the user. alert()
displays a message to the user and waits for the user to dismiss the
dialog. confirm()
displays a
message, waits for the user to click an OK or Cancel button and
returns a boolean value. And prompt()
displays a message, waits for the
user to enter a string, and returns that string. The following code
uses all three methods:
do
{
var
name
=
prompt
(
"What is your name?"
);
// Get a string
var
correct
=
confirm
(
"You entered '"
+
name
+
"'.\n"
+
// Get a boolean
"Click Okay to proceed or Cancel to re-enter."
);
}
while
(
!
correct
)
alert
(
"Hello, "
+
name
);
// Display a plain message
Although the alert()
,
confirm()
, and prompt()
methods are very easy to use, good
design dictates that you use them sparingly, if at all. Dialog boxes
like these are not a common feature on the Web, and most users will
find the dialog boxes produced by these methods disruptive to their
browsing experience. The only common use for these methods today is
debugging: JavaScript programmers sometimes insert alert()
methods in code that is not working
in an attempt to diagnose the problem.
Note that the messages displayed by alert()
, confirm()
, and prompt()
are plain text, not HTML-formatted
text. You can format these dialog boxes only with spaces, newlines,
and punctuation characters.
The confirm()
and prompt()
methods
block—that is, these methods do not return until the user dismisses the dialog boxes they display. ...
Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.