Java Reference
In-Depth Information
concatString = greetingString + “ “ + myName;
document.write(concatString);
</script>
</body>
</html>
2.
If you load it into your web browser, you should see a prompt box asking for your name.
3.
Enter your name and click OK. You should see a greeting and your name displayed twice on
the web page.
You start the script block by declaring three variables. You set the fi rst variable, greetingString, to a
string value. The second variable, myName, is assigned to whatever is entered by the user in the prompt
box. You do not initialize the third variable, concatString, here. It will be used to store the result of
the concatenation that you'll do later in the code.
var greetingString = “Hello”;
var myName = prompt(“Please enter your name”, “”);
var concatString;
In the last chapter, you saw how the web page was represented by the concept of a
document
and that
it had a number of different properties, such as
bgColor
. You can also use
document
to write text and
HTML directly into the page itself. You do this by using the word
document
, followed by a dot, and
then
write()
. You then use
document.write()
much as you do the
alert()
function, in that you
put the text that you want displayed in the web page inside the parentheses following the word
write
.
Don't worry too much about this here, though, because it will all be explained in detail in Chapter 4.
However, you now make use of
document.write()
in your code to write the result of an expression to
the page.
document.write(greetingString + “ “ + myName + “<br>”);
The expression written to the page is the concatenation of the value of the greetingString variable,
a space (“ “), the value of the myName variable, and the HTML <br> tag, which causes a line break. For
example, if you enter Paul into the prompt box, the value of this expression will be as follows:
Hello Paul<br>
In the next line of code is a similar expression. This time it is just the concatenation of the value in the
variable
greetingString
, a space, and the value in the variable
myName
. You store the result of this
expression in the variable
concatString
. Finally, you write the contents of the variable
concatString
to the page using
document.write()
.
concatString = greetingString + “ “ + myName;
document.write(concatString);
Mixing Numbers and Strings
What if you want to mix text and numbers in an expression? A prime example of this would be in the
temperature converter you saw earlier. In the example, you just display the number without telling the
user what it actually means. What you really want to do is display the number with descriptive text
wrapped around it, such as “The value converted to degrees centigrade is 10.”