Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

How to use window.prompt() in JavaScript?

Get support on JavaScript,jQuery, AJAX and other related technology.
Post Reply
Site Admin
Posts: 45

How to use window.prompt() in JavaScript?

Post by admin » Sat Oct 19, 2019 5:21 pm

An easy way to get an input from a user is by using the prompt() method.

Code: Select all

prompt(text, [default]);
text: The text displayed in the prompt box.
default: A default value for the input field (optional).

Code: Select all

var age = prompt("How old are you?");
console.log(age); // Prints the value inserted by the user

If the user clicks the OK button, the input value is returned. Otherwise, the method returns null .
The return value of prompt is always a string, unless the user clicks Cancel , in which that case it returns null .
Safari is an exception in that when the user clicks Cancel, the function returns an empty string. From there, you can convert the return value to another type, such as an integer.

While the prompt box is displayed, the user is prevented from accessing other parts of the page, since dialog
boxes are modal windows.

Starting with Chrome 46.0 this method is blocked inside an <iframe> unless its sandbox attribute has the
value allow-modal.

Post Reply