PrimitiveType

JavaScript Dialog Boxes


There are three simple but useful JavaScript functions for displaying dialog boxes on a web page: alert(), confirm(), and prompt(). These functions are methods of the Window object, though they can be invoked without the window object prefix. The dialog box displayed by each of these functions is modal, meaning that the page behind cannot be brought into focus until the dialog box has been closed.

alert(message)

alert() displays a dialog box with a message and an "OK" button. The function does not return a value when the OK button is clicked. This dialog box is useful for displaying warnings to the user, such as when they need to fill in more data before submitting a form. It is also useful for debugging purposes as you can inform yourself of the value of a variable whilst developing, then remove or comment out the alert() statement when done.

Example:

confirm(question)

confirm() displays a dialog with a message, and two buttons: "OK" and "Cancel". The function returns true if the user clicks OK and false if the user clicks Cancel. This dialog box is useful for getting a confirmation from the user for things such as deleting an entry in a list.

Example:

prompt(message, default)

prompt() displays a dialog box with a message, a text field containing the default text passed to the function, and "OK" and "Cancel" buttons. The function returns the string in the text field when the user clicks OK, or null if the user clicks Cancel. This dialog box is useful for obtaining input from the user without needing to post it to the server using a form.

Example:

Other options

These three functions are very simple and provide some bare-bones functionality for interaction with user. If you need a dialog box with different or more features, or simply one that you can control the appearance of, then your best bet is to look for a JavaScript library that draws these components using JavaScript and CSS. You could opt for an Internet Explorer specific function, showModalDialog(), but of course this will most likely not cover your entire user base.

Closing thoughts

It is tempting for novices to overuse dialog boxes because they are so simple to display. However, it is best to reserve their use for appropriate occasions like those described in the sections above. When used properly, dialog boxes offer useful functionality that can make a web application more desktop-like and responsive in its behaviour.