Home

How to Prompt the User for Input in JavaScript

|
|  Updated:  
2016-03-26 07:26:16
JavaScript Essentials For Dummies
Explore Book
Buy On Amazon

One way to ask a user for data is by using the JavaScript prompt command. To try out the prompt command, open the JavaScript console and type the following:

prompt("What is your name?");

After you press Return or Enter, a pop‐up window appears in your browser window with a text field, as shown here.

Prompting the user for input.
Prompting the user for input.

After you enter your name and click OK, the pop‐up window ­disappears, and the value that you entered in the pop‐up displays in the console, as shown here.

Displaying your name.
Displaying your name.

That's all well and good if all you want to do is capture data and immediately repeat it back like a parrot. But what if you want to do something with the user‐entered data? To do that, you need to store it in a variable.

To store user‐entered data in a variable, you create a new variable and then follow it with =. You then follow it with the prompt statement.

var username = prompt("What is your name?");

It's important to note that a single equal sign (=) in JavaScript is called the assignment operator. Its job is to put the value on the right into the variable on the left.

When you press Return or Enter, a pop‐up window appears in your browser, just as before.

When you enter your name in the pop‐up window and click OK, the JavaScript Console prints out undefined, indicating that the statement is finished and there's nothing else for it to do.

To see the value you just entered, you can type the variable name into the console. JavaScript responds with the value of the variable, as shown here.

Getting the value of a variable from a prompt.
Getting the value of a variable from a prompt.

About This Article

This article is from the book: 

About the book author:

Chris Minnick is an accomplished author, teacher, and programmer. Minnick authored or co-authored over 20 books, including titles in the For Dummies series. He has developed video courses for top online training platforms and he teaches programming and machine learning to professional developers at some of the largest global companies.

Eva Holland is an experienced web developer, tech trainer, and coauthor of Coding with JavaScript For Dummies. She is a co-founder of WatzThis?, a company focused on training and course development.