JavaScript Popup Window

JavaScript has three types of pop-up boxes: alert box, confirmation box, and prompt box.

Warning box

To ensure that information is passed to the user, a warning box is usually used.

When the warning box appears, the user will need to click "OK" to continue.

Syntax

window.alert("sometext");

window.alert(); methods can be used without window to write a prefix.

Example

alert("I am a warning box!");

Try It Yourself

Confirmation box

If you want the user to verify or accept something, you usually use a "confirmation" box.

When the confirmation box appears, the user will have to click "OK" or "Cancel" to proceed.

If the user clicks "OK", the box returns trueIf the user clicks "Cancel", the box returns false.

Syntax

window.confirm("sometext");

window.confirm(); methods can be used without window prefix to write.

Example

var r = confirm("请按按钮");
if (r == true) {
    x = "You clicked OK!";
} else {
    x = "You clicked Cancel!";
}

Try It Yourself

Prompt Box

If you want the user to enter a value before entering the page, you usually use a prompt box.

When the prompt box appears, the user will have to enter a value and then click "OK" or click "Cancel" to continue.

If the user clicks "OK", the box returns the input value. If the user clicks "Cancel", the box returns NULL.

Syntax

window.prompt("sometext",defaultText");

window.prompt() methods can be used without window prefix to write.

Example

var person = prompt("Please enter your name", "Bill Gates");
if (person != null) {
    document.getElementById("demo").innerHTML = "Hello " + person + "! How was your day?";
}

Try It Yourself

Line Break

If you need to display line breaks in a popup box, please add a character after the backslash. n.

Example

alert("Hello\nHow are you?");

Try It Yourself