JavaScript Introduction | Browser Object Model | Dialog Boxes
Dialog Boxes
The window object provides the following methods for creating simple dialog boxes that can be shown to users.
alert()confirm()prompt()
alert() Method
The alert() method of the window object shows a simple message to the user and waits for the user to acknowledge it.
Syntax
window.alert("Simple message");
The user must press the OK button in the dialog box before continuing with any other task.
function alertDialogBox() {
alert("You cannot do anything else until you press OK!");
}
When using any method or property of the window object, you can omit the window prefix.
confirm() Method
The confirm() method of the window object shows a simple message to the user and returns the result as a Boolean value after the user presses OK or Cancel.
Syntax
window.confirm("Simple message");
It returns true if the user presses OK and false if the user presses Cancel.
function confirmDialogBox() {
var str;
if (confirm("Please press OK or Cancel!") == true) {
str = "You pressed OK!";
} else {
str = "You pressed Cancel!";
}
document.getElementById("text").innerHTML = str;
}
prompt() Method
The prompt() method of the window object shows a simple message to the user and returns the string entered by the user.
Syntax
window.prompt("Simple message" + "Default message in the input field");
It returns the text entered in the dialog box as a string.
function promptDialogBox() {
var inputStr = prompt("Please enter your name: ", "Hong Gil-dong");
if (inputStr != null) {
document.getElementById("text").innerHTML = "Your name is " + inputStr + ".";
}
}
In addition to the dialog boxes covered above, you can use the showModalDialog() method to create more complex dialog boxes.
However, all of these dialog boxes forcibly stop browser execution until the user responds. This can be inconvenient for users, so it is better to avoid using dialog boxes too often.