Sometimes, developers need user input using a prompt on the web page. To do so, use the “prompt()” method the browser provides and is supported by JavaScript. You can use the same method if someone asks for input from the user while working in the JavaScript console.
This tutorial will describe the way for creating user input in the JavaScript console.
How to Create User Input in the JavaScript Console?
In the JavaScript console, user input can be created by using the “prompt()” method. This approach displays a dialogue box that requests input from the user. If the user clicks “OK”, it returns the input value, else, it returns null.
Syntax
Use the given syntax for taking user input on the console:
It accepts “text” as a parameter that will be displayed in the dialog box.
Return Value
It returns the entered input value if the user clicks the “OK” button, else its outputs “null”.
Example 1: Create User Input on Console and Store in Variable
In the following example, call the “prompt()” method by passing a text string that will be displayed in the dialog box and store the returned value in a variable “consoleInput”:
The output displays the dialog box that prompts the user for input:
Example 2: Get User Input and Display on Console
Here, for retrieving the entered input value returned by the “prompt()” method, we will call the “alert()” method afterward:
Output
That’s all about creating user input in the JavaScript console.
Conclusion
In the JavaScript console, user input can be created by using the “prompt()” method. If the user clicks on “OK”, it gives the entered value as an output. Otherwise, it gives “null”. For getting the input value, use the JavaScript “alert()” method. This tutorial described the way for creating user input in the JavaScript console.