Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Workshop: Storing User Data in Variables

One common use of variables is to store information that comes from the user. As an example, you will now create a script that prompts the user for information and creates an HTML document containing that information.

In this script, we'll create a customized home page for the user. (It won't be a good one, but it will be customized.) You will use the prompt function to prompt for each piece of information. This function is similar to alert, but prompts the user for an entry.

To begin the script, you will prompt for a first name, a last name, and a title for the page. These statements prompt for three variables:

first = prompt("Enter your first name.");
last = prompt("Enter your last name.");
title = prompt("Enter a page title.");

You can now use the contents of the variables to customize the HTML document. Begin with the title the user entered:

document.write("<h1>" + title + "</h1>");

This statement adds the title to the page, enclosed in <h1> (heading 1) tags. Next, we'll make use of the first and last names to give the user credit:

document.write("<h2>By " + first + " " + last + "</h2>");

This begins with an <h2> tag, followed by the word "By", the first name, a space, the last name, and the closing </h2> tag.

To complete this script, add the usual <script> tags and an HTML framework. Listing 4.5 shows the final HTML document.

Example 4.5. A script to create a customized HTML document

<html>
<head>
<title>Customized home page</title>
</head>
<body>
<script LANGUAGE="JavaScript" type="text/javascript">
first = prompt("Enter your first name.");
last = prompt("Enter your last name.");
title = prompt("Enter a page title.");
document.write("<h1>" + title + "</h1>");
document.write("<h2>By " + first + " " + last + "</h2>");
</script>
<p>This page is under construction.</p>
</body>
</html>

To test this script, load the HTML document into a browser. You will be prompted for the three items, one at a time. After you have entered all three, the complete page is displayed. The final page should resemble Figure 4.2.

04fig02.jpg

Figure 4.2 The customized HTML page script as seen by Netscape.

Share ThisShare This

Informit Network