O'Reilly logo

JavaScript™ 1.5 by Example by Kathie Kingsley-Hughes, Adrian Kingsley-Hughes

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using the prompt() Method to Assign a Value to a Variable

So far, you've seen examples of how to assign values to variables directly in the JavaScript. Sometimes, though, you can't do this. For example, if you ask the user a question, such as her name, you have no possible way to know what the answer might be (unless perhaps you have only one person visiting your site!).

Fortunately, assigning values to variables in mid-script is easy. The following example shows you how to use the prompt() method to accomplish this.

You once again begin with your blank HTML template page and into the <script> block add the prompt() method:

 <html> <head> <title>A Simple Page</title> <script language="JavaScript"> <!-- Cloaking device on! prompt(); // Cloaking ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required