- How to get user input from JavaScript console
- Getting user input from the browser console
- Getting user input from the NodeJS console
- Getting user input from NodeJS using prompt-sync module
- Learn JavaScript for Beginners 🔥
- About
- Search
- Tags
- Взаимодействие с пользователем: alert, prompt, confirm
- alert
- prompt
- confirm
- Особенности встроенных функций
- Резюме
- 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
- JavaScript How to Ask User for Input (A Complete Guide)
- Prompt Box in JavaScript
- How to Store User Input in JavaScript
- Hello!
- Conclusion
- Window prompt()
- Note
- See Also:
- Syntax
- Parameters
- Return Value
- More Examples
- Browser Support
How to get user input from JavaScript console
There are two ways of getting user input from JavaScript depending on whether you want to get the input from the browser or NodeJS. This tutorial will help you to learn both.
Getting user input from the browser console
To ask for user input from the browser, you need to use the prompt() method provided by the browser.
The prompt() method allows you to accept user input as a string and store it on a variable as follows:
The method also accepts a string as additional information to let the user know what kind of input your application is expecting.
For example, write the following code to ask for the user’s name:
Or write the following hint when you need to know the user’s age:
The prompt() will be displayed by the browser as follows:
Then the alert() method will show the result as follows:
You can style the string text as a question or a hint depending on your requirements.
Getting user input from the NodeJS console
To accept user input from NodeJS console, you need to use the provided readline module.
You can require() the module as follows:
Then, you need to create an Interface instance that is connected to an input stream. You create the Interface using readline.createInterface() method, while passing the input and output options as an object argument.
Because you want the input and output to be written to the console, you need to write the input as process.stdin and output as process.stdout
Here’s an example of creating the readline interface:
To ask for user input, you need to call the question() method from the Interface instance, which is assigned to rl variable on the code above.
- The string question you want to ask your user
- The options object (optional) where you can pass the ‘abort’ signal
- The callback function to execute when the answer is received, passing the answer to the function
You can skip the options object and pass the callback function as the second parameter.
Here’s how you use question() the method:
Finally, you can close the rl interface by calling the rl.close() method inside the callback function:
Save the file as ask.js , then call the script using NodeJS like this:
And that’s how you can ask for user input using NodeJS readline module.
You can also use the AbortController() from NodeJS to add a timer to your question and cancel it when a certain amount of time has passed.
But please be aware that the AbortController() method is only available for NodeJS version 15 and up. And even then, the method is still experimental.
The following question will be aborted when no answer was given in 10 seconds after the prompt. The code has been tested to work on NodeJS version 16.3.0 and up:
You can add the timer like in the code above for time-sensitive questions.
As you can see from the example above, the readline module is quite complex compared to the easy prompt() method from the browser.
Alternatively, you can use the npm prompt-sync module to ask for user input without using the readline module.
Getting user input from NodeJS using prompt-sync module
First, you need to install the prompt-sync module using npm or Yarn as follows:
Then, you just need to require() the prompt-sync module and use the prompt() method like in the browser.
Take a look at the code below:
Since the method is synchronous, your Node instance will wait for the input before executing the next line. For more information, you can visit the prompt-sync module documentation
Learn JavaScript for Beginners 🔥
Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.
A practical and fun way to learn JavaScript and build an application using Node.js.
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
Взаимодействие с пользователем: alert, prompt, confirm
Материал на этой странице устарел, поэтому скрыт из оглавления сайта.
Более новая информация по этой теме находится на странице https://learn.javascript.ru/alert-prompt-confirm.
В этом разделе мы рассмотрим базовые UI операции: alert , prompt и confirm , которые позволяют работать с данными, полученными от пользователя.
alert
alert выводит на экран окно с сообщением и приостанавливает выполнение скрипта, пока пользователь не нажмёт «ОК».
Окно сообщения, которое выводится, является модальным окном. Слово «модальное» означает, что посетитель не может взаимодействовать со страницей, нажимать другие кнопки и т.п., пока не разберётся с окном. В данном случае – пока не нажмёт на «OK».
prompt
Функция prompt принимает два аргумента:
result = prompt(title, default);
Она выводит модальное окно с заголовком title , полем для ввода текста, заполненным строкой по умолчанию default и кнопками OK/CANCEL.
Пользователь должен либо что-то ввести и нажать OK, либо отменить ввод кликом на CANCEL или нажатием Esc на клавиатуре.
Вызов prompt возвращает то, что ввёл посетитель – строку или специальное значение null , если ввод отменён.
Единственный браузер, который не возвращает null при отмене ввода – это Safari. При отсутствии ввода он возвращает пустую строку. Предположительно, это ошибка в браузере.
Если нам важен этот браузер, то пустую строку нужно обрабатывать точно так же, как и null , т.е. считать отменой ввода.
Как и в случае с alert , окно prompt модальное.
var years = prompt('Сколько вам лет?', 100); alert('Вам ' + years + ' лет!')
Второй параметр может отсутствовать. Однако при этом IE вставит в диалог значение по умолчанию «undefined» .
Запустите этот код в IE, чтобы понять о чём речь:
Поэтому рекомендуется всегда указывать второй аргумент:
confirm
confirm выводит окно с вопросом question с двумя кнопками: OK и CANCEL.
Результатом будет true при нажатии OK и false – при CANCEL( Esc ).
var isAdmin = confirm("Вы - администратор?"); alert( isAdmin );
Особенности встроенных функций
Конкретное место, где выводится модальное окно с вопросом – обычно это центр браузера, и внешний вид окна выбирает браузер. Разработчик не может на это влиять.
С одной стороны – это недостаток, так как нельзя вывести окно в своём, особо красивом, дизайне.
С другой стороны, преимущество этих функций по сравнению с другими, более сложными методами взаимодействия, которые мы изучим в дальнейшем – как раз в том, что они очень просты.
Это самый простой способ вывести сообщение или получить информацию от посетителя. Поэтому их используют в тех случаях, когда простота важна, а всякие «красивости» особой роли не играют.
Резюме
- alert выводит сообщение.
- prompt выводит сообщение и ждёт, пока пользователь введёт текст, а затем возвращает введённое значение или null , если ввод отменён (CANCEL/ Esc ).
- confirm выводит сообщение и ждёт, пока пользователь нажмёт «OK» или «CANCEL» и возвращает true/false .
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.
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.
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 |