window.prompt("Enter your name");
This shows the following modal at the top of your page:
This method takes two arguments:
- Message. The message that asks the user for the input.
- Default input. The default input value before 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.
prompt("Enter your name:", "Alice");
When you run this piece of code, you get a prompt that looks like this:
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 into a variable called nickname.
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:
And there you have it!
To recap, you can ask 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 into a variable.
Thanks for reading.
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
- Artificial Intelligence2023.03.14Best AI Tools of 2023 (Save Time & Boost Productivity)