- Window: prompt() method
- Syntax
- Parameters
- Return value
- Examples
- Notes
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Window prompt()
- Note
- See Also:
- Syntax
- Parameters
- Return Value
- More Examples
- Browser Support
- JavaScript How to Ask User for Input (A Complete Guide)
- Prompt Box in JavaScript
- How to Store User Input in JavaScript
- Hello!
- Conclusion
- prompt ( )
- Пример
- Как пишется
- Как понять
- На практике
- Дока Дог советует
Window: prompt() method
window.prompt() instructs the browser to display a dialog with an optional message prompting the user to input some text, and to wait until the user either submits the text or cancels the dialog.
Under some conditions — for example, when the user switches tabs — the browser may not actually display a dialog, or may not wait for the user to submit text or to cancel the dialog.
Syntax
prompt() prompt(message) prompt(message, defaultValue)
Parameters
A string of text to display to the user. Can be omitted if there is nothing to show in the prompt window.
A string containing the default value displayed in the text input field.
Return value
A string containing the text entered by the user, or null .
Examples
let sign = prompt("What's your sign?"); if (sign.toLowerCase() === "scorpio") alert("Wow! I'm a Scorpio too!"); > // there are many ways to use the prompt feature sign = window.prompt(); // open the blank prompt window sign = prompt(); // open the blank prompt window sign = window.prompt("Are you feeling lucky"); // open the window with Text "Are you feeling lucky" sign = window.prompt("Are you feeling lucky", "sure"); // open the window with Text "Are you feeling lucky" and default value "sure"
When the user clicks the OK button, text entered in the input field is returned. If the user clicks OK without entering any text, an empty string is returned. If the user clicks the Cancel button, this function returns null .
The above prompt appears as follows (in Chrome on macOS):
Notes
A prompt dialog contains a single-line textbox, a Cancel button, and an OK button, and returns the (possibly empty) text the user entered into that textbox.
Please note that result is a string. That means you should sometimes cast the value given by the user. For example, if their answer should be a Number, you should cast the value to Number.
const aNumber = Number(window.prompt("Type a number", ""));
Dialog boxes are modal windows; they prevent the user from accessing the rest of the program’s interface until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box (or modal window).
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 8, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Window prompt()
The prompt() method displays a dialog box that prompts the user for input.
The prompt() method returns the input value if the user clicks «OK», otherwise it returns null .
Note
A prompt box is used if you want the user to input a value.
When a prompt box pops up, the user will have to click either «OK» or «Cancel» to proceed.
Do not overuse this method. It prevents the user from accessing other parts of the page until the box is closed.
See Also:
Syntax
Parameters
Parameter | Description |
text | Optional. The text to display in the dialog box. |
defaultText | Optional. The default input text. |
Return Value
Parameter | Description |
A string | If the user clicks «OK», the input value is returned. Otherwise null is returned. |
More Examples
Prompt for his favourite drink:
let text;
let favDrink = prompt(«What’s your favorite cocktail drink?»);
switch(favDrink) case «Coca-Cola»:
text = «Excellent choice! Coca-Cola is good for your soul.»;
break;
case «Pepsi»:
text = «Pepsi is my favorite too!»;
break;
case «Sprite»:
text = «Really? Are you sure the Sprite is your favorite?»;
break;
default:
text = «I have never heard of that one!»;
>
Browser Support
prompt() is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
JavaScript How to Ask User for Input (A Complete Guide)
To ask for user input in JavaScript, use the built-in window.prompt() method.
window.prompt("Enter your name");
This shows the following modal at the top of your page:
Prompt Box in JavaScript
To ask for user input in JavaScript, you can use the built-in prompt box. To show a prompt, use the prompt() method.
This method takes two arguments:
- Message. The message that asks the user for input.
- Default input. The default input value before the user types anything. This is an optional argument.
The prompt() method returns the user input as a string. If no input is specified, it returns a null.
Here is an example of a prompt in JavaScript:
prompt("Enter your name:", "Alice");
When you run this piece of code, you get a prompt that looks like this:
How to Store User Input in JavaScript
If you ask for user input, you may also want to store it somewhere. To store the input, just assign it to a new variable.
var nickname = prompt("Enter a name you want to be called");
Now, when a user enters their name and clicks “OK” in the modal, their name will be stored in a variable called nickname.
For instance, let’s create a simple page that asks a user for a name and displays a greeting on the front page. Let’s create a file called index.html on the desktop and add the following HTML/JavaScript there:
Hello! var nickname = prompt("Please enter your name: "); if (nickname != null)
When you open up the index.html page, you are going to see a prompt at first:
When you enter a name into it, you are going to see the name appear on the front page:
Conclusion
Today you learned how to ask for user input in JavaScript.
To recap, you can ask for user input with the built-in prompt() method. This opens up a prompt box where a user can enter text input. To store this input, assign the prompt to a variable.
prompt ( )
При помощи функции prompt ( ) можно вывести на экран пользователя модальное окно c полем ввода и текстом-пояснением.
🤖 Из-за того, что окно модальное — работа с интерфейсом браузера и страницами будет заблокирована. Это неудобно, плюс может восприниматься пользователем как попытка ограничивать его свободу. Модальное окно для пользователя — окно, которое блокирует работу пользователя с браузером до тех пор, пока пользователь это окно не закроет.
Пример
Скопировать ссылку «Пример» Скопировано
💡 Это крайне быстрый вариант кода, который взаимодействует с пользователем, но окно созданное таким образом не изменяется через CSS, а значит использовать его лучше только для прототипирования интерфейса. В финальном варианте веб-страницы юзать модальное окно нежелательно.
Как пишется
Скопировать ссылку «Как пишется» Скопировано
prompt ( ) принимает 1 или 2 аргумента — это текст для отображения и значение по умолчанию для поля ввода.
Результат работы prompt ( ) можно записать в переменную:
const answer1 = prompt('Как тебя зовут?')const answer2 = prompt('Как тебя зовут?', 'Имя')
const answer1 = prompt('Как тебя зовут?') const answer2 = prompt('Как тебя зовут?', 'Имя')
Если при вызове prompt ( ) использовать только один параметр, тогда в появившемся окне поле ввода не будет содержать «подсказки» ввода.
В случае когда использовано два параметра, то в поле ввода будет с подсказкой ввода. Это полезно, чтобы показать пользователю, какой результат ввода ожидается.
Как понять
Скопировать ссылку «Как понять» Скопировано
Аргументы prompt ( ) должны быть строками. Если это не так — будет автоматическое приведение к строке. Такое поведение не доставляет проблем, пока аргумент является примитивом или встроенным типом, имеющим правила приведения к строке.
prompt('Как тебя зовут?', 'Саша')// Текст: 'Как тебя зовут?', значение поля ввода: 'Саша'prompt('Введите возраст', 18)// 'Введите возраст', СТРОКА '18'
prompt('Как тебя зовут?', 'Саша') // Текст: 'Как тебя зовут?', значение поля ввода: 'Саша' prompt('Введите возраст', 18) // 'Введите возраст', СТРОКА '18'
💡 Результат prompt ( ) — строка, если была нажата кнопка «OK» или null , если была нажата «Отмена».
Поэтому не стоит полагаться на то, что результат prompt ( ) всегда будет строкой. Это может привезти к ошибкам в работе скрипта, например:
const result = prompt('Введите четное число', '')// вводим ДЕСЯТЬ и нажимаем ОКif (result % 2 === 0) // Проверка на четность alert('Число четное')> else alert('Число нечетное')> // Результат: сообщение 'Число нечетное'
const result = prompt('Введите четное число', '') // вводим ДЕСЯТЬ и нажимаем ОК if (result % 2 === 0) // Проверка на четность alert('Число четное') > else alert('Число нечетное') > // Результат: сообщение 'Число нечетное'
С точки зрения синтаксиса ошибок нет, но
- Нет явной обработки null — result примет значение null в случае нажатия кнопки «Отмена»: Конечно null % 2 выполнится без ошибок, но работа программы будет некорректной. Правильнее будет обработать и отказ от ввода числа.
- Нет обработки ситуаций, когда введено не число.
В операции (result % 2 = = = 0 ) из-за деления на 2 JavaScript осуществляет приведение строки result к численному типу. Если не получится, то результат работы будет некорректным.
Более корректный вариант обработки ввода:
var result = prompt('Введите четное число', '')if (result === null) alert('Вы отказались от ввода')> else if (isNaN(result % 2)) alert('Ошибка, введено НЕ ЧИСЛО')> else if (result % 2 === 0) alert('Число четное')> else alert('число нечетное')>
var result = prompt('Введите четное число', '') if (result === null) alert('Вы отказались от ввода') > else if (isNaN(result % 2)) alert('Ошибка, введено НЕ ЧИСЛО') > else if (result % 2 === 0) alert('Число четное') > else alert('число нечетное') >
Вариант обработки всех возможных случаев ввода более громоздкий, но он намеренно написан наиболее простым способом. В случае использование switch или отдельных самостоятельно написанных функций проверки код примет более элегантный вид.
На практике
Скопировать ссылку «На практике» Скопировано
Дока Дог советует
Скопировать ссылку «Дока Дог советует» Скопировано
🛠 Ниже представлен пример использования prompt ( ) с самостоятельно созданным диалоговым окном: