Window prompt() Method

Definition and usage

prompt() The method displays a dialog box, prompting the user to enter.

If the user clicks "OK", then prompt() The method returns the input value, otherwise it returns null.

Note

If you want the user to enter a value, use the prompt box.

When the popup dialog box appears, the user must click "OK" or "Cancel" to continue.

Do not overuse this method. It will prevent the user from accessing other parts of the page before closing the box.

See also:

alert() method

confirm() method

Instance

Example 1

Prompt for username and output message:

let person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
  document.getElementById("demo").innerHTML =
  "Hello " + person + "! How are you today?";
}

Try it yourself

Example 2

Prompt for his favorite drink:

let text;
let favDrink = prompt("What is your favorite drink?");
switch(favDrink) {
  case "Coca-Cola":
    text = "Great choice! Coca-Cola is good for your soul.";
    break;
  case "Pepsi":
    text = "Pepsi is also my favorite!";
    break;
  case "Sprite":
    text = "Really? Are you sure Sprite is your favorite?";
    break;
  default:
    text = "I have never heard of that!";
}

Try it yourself

Syntax

prompt(message, default)

Parameter

Parameter Description
message Required. The text to be displayed in the dialog.
default Optional. Default input text.

Return value

Type Description
String

If the user clicks "OK", it returns the input value.

If the user does not enter any string, it returns an empty string.

otherwise, it returns null.

description

prompt() The method will display a specified message in a dialog box message, this dialog contains a text input field, an OK button, and a cancel button, where the graphical elements determined by the platform explain to the user what needs to be entered.

If the user clicks the cancel button,prompt() the method will return null. If the user clicks the confirm button,prompt() it will return the current text displayed in the input field.

by prompt() The dialog displayed by the method is modal, which means it will block all input from the browser window until the user clicks the confirm button or cancel button to close it. Since the value returned by this method is determined by the user's response, it is called prompt() at this time, the execution of JavaScript code will be paused. The next statement will not be executed until the user responds.

Browser Support

All Browsers Support prompt():

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support Support Support Support Support Support