Confirm Boxes
A confirm box is one of the ways of soliciting user input
into scripts. The confirm() method produces a message
box that gives the user a choice.
Along with a displayed message, "OK" and "Cancel" buttons are displayed for user response. A
script, then, can take different courses of action depending on which of these two buttons
the user clicks. The general format for the confirm() method is shown
below.
variable = [window.]confirm("message")
Figure 3-25. General format for confirm() method.
This is a method of the window object, which is understood and need
not be coded as part of the method reference. A confirm box returns a Boolean value. If the user
clicks the "OK" button, then true is returned; if the user clicks
the "Cancel" button, false is returned. A script, then, can test
the returned value and take different processing actions depending on the choice.
The following button illustrates the capture and display of the value returned by the
confirm() method.
<script type="text/javascript">
function GetConfirm() {
var ReturnedValue = confirm("Are you sure?");
alert("Returned value is " + ReturnedValue);
}
</script>
<input type="button" value="Show Confirm" onclick="GetConfirm()"/>
Listing 3-20. Displaying returned values from the confirm() method.
When the button is clicked, a confirm box is displayed with the message "Are
you sure?" When the "OK" or "Cancel" button is clicked, the returned true
or false value is assigned to variable ReturnedValue.
Then this value is displayed in an alert box.
Confirm boxes normally are used to solicit user input and to take alternate processing steps
depending on the returned value. Therefore, they are used in conjunction with program decision
making, a topic that is presented later. An example of how this works, though, is the following
script, which sets the text of the page to larger or normal size depending on the user's response
to a confirm() choice.
window.onload = init;
function init() {
var SetText = document.getElementById("SetText");
SetText.onclick=TextSize;
}
function TextSize() {
var ReturnedValue = confirm("Larger text?");
if (ReturnedValue == true) {
document.body.style.fontSize = "1em";
}
else {
document.body.style.fontSize = ".83em";
}
}
<input type="button" value="Set Text" id="SetText">
Listing 3-21. Testing confirm box conditions.
In summary, textboxes, prompt boxes, and confirm boxes are three common ways in which users
provide input data or processing choices to scripts. Textboxes, alert boxes, and HTML tags
offering innerHTML properties
can be used as display areas for script output. As you will discover later, there are additional,
more specialized methods of user interaction that supplement these basic techniques.