HTML and CSS Reference
In-Depth Information
EXAMPLE 4.3
<html>
<head>
<title>Using the JavaScript prompt box</title>
</head>
<body>
<script type = "text/javascript">
1
var name=prompt("What is your name?", "");
alert("Welcome to my world! " + name);
2
var age=prompt("Tell me your age.", "Your age: ");
3
if ( age == null){ // If user clicks the Cancel button
alert("Not sharing your age with me");
}
else{
4
alert(age + " is young");
}
5
alert(prompt("Where do you live? ", ""));
</script>
</body>
</html>
EXPLANATION
1
The prompt() method takes two arguments, one is the text that will prompt the
user to respond. This text will appear above the prompt dialog box. The second
argument provides default text that will appear at the far left, inside the box. If the
second argument is an empty string, the prompt box will be empty. After the user
types his or her response in the prompt textbox, the response is returned and as-
signed to the variable name . The alert() method displays that value on the screen.
2
The variable called age will be assigned whatever the user types into the prompt
box. This time a second argument, “Your age: ” , is sent to the prompt() method.
When the prompt box appears on the screen, Your Age: will appear inside the box
where the user will type his or her response.
3
If the user clicks the Cancel button, the value returned by the prompt() method is
null . This if statement tests to see if the value of age is null .
4
If the return value was null , this line is printed in the alert dialog box.
5
The prompt() method is sent as an argument to the alert() method. After the user
has clicked OK in the prompt box, the return value is sent to the alert() method,
and then displayed on the screen. See Figures 4.3 through 4.7.
Search WWH ::




Custom Search