Export (0) Print
Expand All

Using Message Boxes (JavaScript)

Message boxes display information to users or request input before completing a procedure.

Use alert, confirm, and prompt message boxes to obtain input from the user.

The boxes are methods of the interface window object. Because the window object is at the top of the object hierarchy, you do not have to use the full name (for example, window.alert()) of any of these message boxes. However, it is a good idea to use the full name, because it helps you remember which object the methods belong to.

Alert Message Box

The alert method has one argument, the string of text you want to display to the user. The string is not HTML. The message box provides an OK button so the user can close it. The message box is modal, that is, the user must close it before continuing.

The following example illustrates use of the alert method.

window.alert("Welcome! Press OK to continue.");

Confirm Message Box

The confirm message box lets you ask the user a "yes-or-no" question, and gives the user the option of clicking either an OK button or a Cancel button. The confirm method returns either true or false. This message box is also modal: the user must respond to it (click a button), and thereby close it, before proceeding.

The following example illustrates use of the confirm method.

var result = window.confirm("Click OK or Cancel.");
if (result)
    window.alert("You clicked OK");
    window.alert("You clicked Cancel");

Prompt Message Box

The prompt message box provides a text field in which the user can type an answer in response to your prompt. This box has an OK button and a Cancel button.

If you provide a second string argument, the prompt message box displays that second string in the text field as the default response. Otherwise, the default text is "<undefined>".

The prompt method displays a modal message box. The user must close it before continuing.

The following example illustrates use of the prompt method.

var response = window.prompt("Welcome!","Enter your name here.");
© 2014 Microsoft