Javascript Confirm
The Javascript confirm function is very similar to the Javascript alert function. A small dialogue box pops up
and appears in front of the web page currently in focus. The confirm box is different than the alert
box in that it supplies the user with a choice, they can either press OK to confirm the popups message or
they can press cancel and not agree to the popups request.
Confirmation are most often used to confirm an important action that is taking place on a website.
For example they may be about to submit an order or about to visit a link that will take them away from the
current website.
Javascript Confirm Example
Below is an example of how you would use a confirm dialogue box to warn the user about something, and they
could either continue on or stay put.
HTML & Javascript Code:
<html>
<head>
<script type="text/javascript">
<!--
function confirmation() {
var answer = confirm("Leave tizag.com?")
if (answer){
alert("Bye bye!")
window.location = "http://www.google.com/";
}
else{
alert("Thanks for sticking around!")
}
}
//-->
</script>
</head>
<body>
<form>
<input type="button" onclick="confirmation()" value="Leave Tizag.com">
</form>
</body>
</html>
Display:
Note the part in red, this is where all the magic happens. We call the confirm function with the message, "Leave Tizag?".
Javascript then makes a popup window with two choices and will return a value to our script code depending on which
button the user clicks.
Confirm returns the value 1 if the user clicks OK and the value 0 if the
user clicks Cancel. We store this value in answer by setting it
equal to the confirm function call.
After answer has stored the value, we then use answer as a conditional statement.
If answer is anything but zero, then we are going to send the user away from Tizag.com.
If answer is equal to zero, then we will keep the user at Tizag.com because they clicked
the Cancel button.
In either case we have a Javascript alert box that appears to inform the user what is going to happen.
"Bye bye!" if they chose to leave and "Thanks for sticking around!" if they chose to stay.
In this lesson we also used the window.location property for the first time. Whatever
we set window.location to will be where the browser is redirected to. In this example we chose Google.com.
We will discuss redirection in greater detail later on.
|