Built-in Functions: alert, confirm, prompt
Join the Discussion
JavaScript has three functions that are predefined for you. They provide a way for to request that the browser display one of three predefined dialog boxes. A dialog box is a small window that opens in front of the main window. You need to close that window again before being allowed back to the main window. Dialog boxes are sometimes called modal windows.
Each of these three dialog boxes provides a way for you to
- display information that is not a part of the web page,
- ask a question, or
- collect information
With each of these functions, the JavaScript processing stops until your visitor closes the dialog box.
Alert
The alert function displays information in a dialog box. This function is useful for displaying the results of your JavaScript processing where you don't want to go to update the web page itself. You can use this to display error messages after validating a form so highlight that there are errors.
The alert function is also useful when you are testing your JavaScript. You can use it to display the value held in a variable at that stage in the processing.
alert('I got here');
An alert dialog box displays an OK button that needs to be pressed in order for the JavaScript to continue running. This acts as a confirmation that the message that the alert displayed has actually been seen.
An alert dialog box
Note that in some web browsers (for example Opera 9) an alert box also provides an extra option allowing all of the remaining JavaScript on the current web page to be disabled. This makes the alert function more useful for you to assist in testing your script and less useful for displaying information to your visitors.
some alert dialogs allow you to stop further JavaScript from running
Confirm
The confirm function is more advanced that the alert function. As well as displaying a message , the function also reurns true or. It does this by displaying two buttons at the bottom of the dialog box OK and Cancel. When the OK button is pressed the button returns true. When Cancel is pressed the function returns false. This allows you to interrupt your JavaScript processing to ask your visitor a question and then continue processing based on which button they press.
A confirm dialog box
Note that as with the alert dialog box, Opera 9 also provides the option of completely disabling all subsequent JavaScript processing on the web page when displaying a confirm dialog box.
Prompt
The third of the functions that are predefined in JavaScript is the prompt function. Prompt is the most advanced of these because it accepts two parameters instead of one. It returns a text string when OK is selected. and null when Cancel is selected.if (!name) name = 'Hey You!';
A prompt dialog box
Yet again Opera 9 offers your visitor the opportunity to disable all JavaScript processing on the page when a prompt dialog box is displayed.



