Alert Boxes
Earlier you were introduced to the alert() method as a quick and
easy way to display information generated by a script. This is a method of the
window object and has the following general format.
[window.]alert(number|string|variable|method()|expression)
Figure 3-22. General format for alert() method.
The window reference that prefixes this method is understood in this
context and need not be included in the reference. The alert() method
contains the message to be displayed enclosed inside parentheses. You can display numbers, text
strings, variables, other methods, and/or arithmetic or string expressions. Any or all of these
values can be concatenated to produce an extended message. You cannot, however, include HTML
tags or style sheet settings in the message string. The following displays demonstrate
various uses of the alert() method.
Figure 3-23. Example alert() methods.
When composing an alert() statement with a quoted text string, there
can be no line breaks in the string caused by continuation of the text from one line to the
next. The following alert() method, for example, is invalid.
alert ("This is an alert box. It can be used to provide short messages or
computational results to users. Alert boxes can be displayed through
an inline script or through a function called by an event handler.");
Listing 3-15. Invalid coding of alert() method.
If you do not wish to type the long string of text as a single line, you need to break the
text into substrings and concatenate them to compose the complete alert()
method.
window.onload = init;
function init() {
var ShowAlert = document.getElementById("ShowAlert");
ShowAlert.onclick = ShowMsg;
}
function ShowMsg() {
alert("This is an alert box. It can be used to provide short messages " +
"or computational results to users. Alert boxes can be displayed " +
"through an inline script or through a function called by an " +
"event handler.");
}
<input type="button" value="Show Alert Box" id="ShowAlert">
Listing 3-16. Valid coding of alert() method.
For certain extended text messages you may wish to display them with line breaks rather than
permitting the alert() box to expand to its default width. The special
character code "\n" inserts a line break into a text string.
Below is the previous output displayed with embedded line-break characters.
window.onload=init;
function init() {
var ShowAlert = document.getElementById("ShowAlert");
ShowAlert.onclick = ShowMsg();
}
function ShowMsg() {
alert("This is an alert box. It can be used to provide short messages\n" +
"or computational results to users. Alert boxes can be displayed\n" +
"through an inline script or through a function called by an\n" +
"event handler.");
}
<input type="button" value="Show Alert Box" id="ShowAlert">
Listing 3-17. Displaying an alert box with line breaks.