Javascript Pop-up Boxes - Confirm Box
(Page 3 of 4 )
If you want to give a user an option, you can use the Confirm Box. The user will have the choice of saying OK or Cancel. Here it is in code:
<html>
<head>
<script type="text/javascript">
function disp_confirm()
{
var r=confirm("Choose Wisely")
if (r==true)
{
document.write("Oh No! Now you did it!")
}
else
{
document.write("You canceled your paycheck!")
}
}
</script>
</head>
<body>
<input type="button" onclick="disp_confirm()" value="Click Me Fool" />
</body>
</html>
You will notice a few new things in the above example. Don't fret about those too much for now. First, we added a Function, which we will hopefully learn to do later in this tutorial. We also added a button to the page as well, that says: Click Me Fool.
This particular Confirm Button doesn't trigger when the page loads, although it could. Instead, we use our Click Me Fool button to have the user trigger it. When they click it the following pop-up appears:

If the user clicks OK, it will print the following to the screen:
Oh NO! Now you did it!
If the user clicks the CANCEL button, the following prints to the page:
You canceled your paycheck!
The confirm button relies on a boolean value stored in a variable called r. If the user clicks on the OK (or true), it does one thing, if they choose CANCEL (or false) it does another.
You can also do this with a page load instead of having the user click on a button:
<html>
<head>
<script type="text/javascript">
{
var r=confirm("Choose Wisely")
if (r==true)
{
document.write("Oh No! Now you did it!")
}
else
{
document.write("You canceled your paycheck!")
}
}
</script>
</head>
<body>
</body>
</html>
Next: Prompting the Prompt Box >>
More JavaScript Articles
More By James Payne