Latest web development tutorials
 

Window prompt() Method

< Window Object

Example

Display a prompt box which ask the user for her/his name, and output a message:

var person = prompt("Please enter your name", "Harry Potter");

if (person != null) {
    document.getElementById("demo").innerHTML =
    "Hello " + person + "! How are you today?";
}
Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

The prompt() method displays a dialog box that prompts the visitor for input.

A prompt box is often used if you want the user to input a value before entering a page.

Note: When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. Do not overuse this method, as it prevent the user from accessing other parts of the page until the box is closed.

The prompt() method returns the input value if the user clicks "OK". If the user clicks "cancel" the method returns null.


Browser Support

Method
prompt() Yes Yes Yes Yes Yes

Syntax

prompt(text,defaultText)

Parameter Values

Parameter Type Description
text String Required. The text to display in the dialog box
defaultText String Optional. The default input text

Technical Details

Return Value: A String. If the user clicks "OK", the input value is returned. If the user clicks "cancel", null is returned. If the user clicks OK without entering any text, an empty string is returned.

Examples

More Examples

Example

Using the switch statement together with prompt() to execute a block of code based on user input:

var text;
var favDrink = prompt("What's your favorite cocktail drink?");
switch(favDrink) {
    case "Martini":
        text = "Excellent choice! Martini is good for your soul.";
        break;
    case "Daiquiri":
        text = "Daiquiri is my favorite too!";
        break;
    case "Cosmopolitan":
        text = "Really? Are you sure the Cosmopolitan is your favorite?";
        break;
    default:
        text = "I have never heard of that one..";
        break;
}
Try it Yourself »

Related Pages

Window Object: href="met_win_alert.html">alert() Method

Window Object: href="met_win_confirm.html">confirm() Method


< Window Object