HTML and CSS Reference
In-Depth Information
Edit the variablewrite.html document as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="" lang="en" xml:lang="en">
<title>JavaScript Practice</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<h1>Using JavaScript</h1>
<script type="text/javascript">
<!-- <![CDATA[
var userName;
userName = "Karen";
document.write("<h2>Hello " + userName + "</h2>");
// ]]> -->
Be sure to remove the <h2> and </h2> information above and below the script block.
Save the file as variablewrite2.html and display it in the browser window. You should
not see any difference in the document in the browser.
Collecting Variable Values Using a Prompt
To demonstrate the interactive aspect of JavaScript and variables, we can use the
prompt() method to request data from the user, and write this data to the Web page.
For example, we will build on Hands-On Practice 14.4 and prompt the user for a name
rather than hard code this data in the userName variable.
The prompt() method is a method of the window object. We could use
window.prompt() but the window object is assumed, so we can write this as simply
prompt() . The prompt() method can provide a message to the user. This method is
generally used in conjunction with a variable, so that the incoming data is stored in a
variable. The structure looks as follows:
someVariable = prompt("prompt message");
When this command executes, a prompt box pops up that displays the message and an
input box for data entry. The user types in the prompt box, clicks the OK button, and
the data is assigned to the variable.
Let's add this feature to the variablewrite2.html file.
In this Hands-On Practice you will use the prompt() method to gather data from the
user and write it to the document.
Search WWH ::

Custom Search