Prompt in JavaScript Tutorial

In this section, we will learn what the window prompt() method is and how to use it in JavaScript.

JavaScript Window prompt() Method: (How to get input from user in JavaScript)

The `prompt()` function is a way of creating an input box and asking users to enter a value.

Notes:

  • The dialog that will appear to the user is synchronous. This means code execution stops when a dialog is displayed, and resumes after it has been dismissed.
  • Also, the shape of this dialog is system dependent and we can’t change it via CSS.

The dialog box of the `prompt` function has two buttons:

  • OK
  • Cancel

If a user enters a value and hits the `OK` button, the return value of the function will be the value that user entered. On the other hand, if the user canceled the dialog box, the return value will be `null`.

Window prompt() Method Syntax:

prompt(text, defaultText)

Window prompt() Method Parameter

The function takes two arguments:

  • The first argument is the message that we want users to see (Usually this message explains what type of data users should enter etc.)
  • The second argument is the default value that will appear on the text box of the dialog box, which is basically an example of the type of value that users should enter into the box. This value is optional and we can simply ignore it.

Window prompt() Method Return Value

If a user enters a value and hits the `OK` button, the return value of the function will be the value user entered. On the other hand, if the user canceled the dialog box, the return value will be `null`.

Example: prompting in JavaScript

let name = prompt("What's your name?");
if (name){
  alert(`Welcome ${name}`);
}else{
  alert(`Anonymous person entered the website`);
}

Example: input box in JavaScript

let name = prompt("What's your name?" , "John Doe");
if (name){
  alert(`Welcome ${name}`);
}else{
  alert(`Anonymous person entered the website`);
}
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies