English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript basic tutorial

JavaScript object

JavaScript function

JS HTML DOM

JS browser BOM

AJAX basic tutorial

JavaScript reference manual

JavaScript Pop-ups

In JavaScript, you can create dialog boxes or pop-ups to interact with users.

JavaScript has three different types of popup boxes: alert box, confirmation box, and prompt box.

Alert box

The alert box is the simplest popup box. It allows you to display a short message to the user.

It also includes an 'OK' button, which the user must click to proceed.

Syntax:

window.alert("msg")

window.alert()The method can be used without the prefix "window.", and can be used directly:

alert("Hello world!");
Test and See‹/›

Confirmation box

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

The confirmation box looks similar to the alert box, but it contains a 'Cancel' button and an 'OK' button.

. If the user clicks 'OK', the box returnstrue. If the user clicks 'Cancel', the box returnsfalse.

Syntax:

window.confirm("msg")

window.confirm()The method can be used without the prefix "window.", and can be used directly:

var r = confirm("Press a button!");
if (r == true) {
   txt = "You clicked OK!";
}
   txt = "You clicked Cancel!";
}
Test and See‹/›

Prompt box

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

The prompt box includes a text input field, 'OK' and 'Cancel' buttons.

If the user clicks 'OK', the box will return the input value. If the user clicks 'Cancel', the box will return null.

Syntax:

window.prompt("msg", "defaultText")

window.prompt()The method can be used without the prefix "window.", and can be used directly:

var name = prompt("Please enter your name", "Someone");
if (name != null) {
   document.getElementById("output").innerHTML = "Hello " + name;
}
Test and See‹/›

Note:prompt()The value returned by the method is always a string. This means that if the user enters15, it will return the string “ 15”instead of a number15.

Therefore, if you are going to use the return value as a number, you must convert it, seeHow to Convert Data Types in JavaScript.

Displaying a Newline Character in a Dialog Box

To display a newline character in a dialog box, use a newline character or newline character (\n); followed by the character n.

alert("Hello\nHow are you?");
Test and See‹/›

More Examples

This example demonstrates the different types of dialog boxes supported by JavaScript:

Click the button below to display different dialog boxes:


Run Code