Friday, May 8, 2009

JavaScript Confirm Box Dialog



The confirm box, has a syntax that is similar to that of alerts. It is often used when you want ask the user to make a decision on something. It has an "OK" and a "Cancel" button.

If the user clicks "OK", the value returned is true. If the user clicks "Cancel", false is returned. These boolean values can be used for further script execution. Once again, they are usually placed either within the <head> tag or the <body> tag as is the case here. It is not required, but is good style as it makes the page flow efficiently and gives it a professional look :


<head>
<script type="text/javascript">
function userConfirm()
{
var response=confirm("Press a button");
if (response==true)
{
document.write("OK button!");
}
else
{
document.write("Cancel button!");
}
}
</script>
</head>


Note here that in 'var response=confirm("Press a button");' above, we use an equal sign to assign a value to the variable 'response'. Note in the next line that 'if (response==true)' uses double equal signs to indicate equals and also unlike AppleScript the word 'then' is omitted.

'document.write("OK button!");' tells the function to write "You pressed OK!" to the web page (or blog). The text string must be enclosed by quotes and parenthesis.




<body>
<input type="button" onclick="userConfirm()" value="Display confirm dialog" />
</body>


This is very similar to the alert syntax and should be easy to understand.




The button above would show this dialog:

confirmAlert


If you have questions or would like to suggest a post, contact me at: hyperscripter@gmail.com or http://twitter.com/hyperscripter

What is this??