Web Design
Web Design Surrey Web Design Services in Surrey

Tutorial Categories

Links & Services

Mailing List

For special offers and annoucements, please enter your email address below.

JavaScript Confirmation Dialogues

In this tutorial I'm going to show you how to make a confirmation dialogue box that asks a user if the would like to navigate away from the page. I'll also show you how to add newlines and escape quotes correctly. The result will look like this:

STEP 1:

You will need to add the script and the button as follows (please follow the comments in the code).

<?php /* Javascript Confirmation Dialogues */ ?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Confirmation Dialogue Boxes</title> 
<script type="text/javascript"> 
<!-- 

//Create a New Function called myConfirmBox() 
function myConfirmBox(){ 

//show the dialogue and store the answer in a variable called "answer"  
var answer = confirm("Do you want leave this page? \nNote:Pressing \"Cancel \" will keep you on the same page "); 
     
    //so now we create a simple "if...else" statement that will do something depending on which button was clicked 
    //if the answer is "true" then the user pressed "ok" 
    if (answer == true) { 
    //so redirect them to another page 
    window.location="http://www.marcfirth.co.uk/portfolio.php"; 
    //otherwise, the user pressed "cancel" 
    } else { 
    //so we "return false" - in other words: do nothing. 
    return false; 
    } 
     
//and don't forget to close the function 
} 
//--> 
</script> 
</head> 

<body> 
<form> 
<!-- Here we have a form button with it's "onclick" event set to call our JavaScript function --> 
<input type="button" value="Go!" onclick="myConfirmBox()"> 
</form> 
</body> 
</html>

NOTES:

Firstly, notice the use of \\n half way through the question in the dialogue box. "n" allows you to create newlines in your dialogue box.

Secondly, notice the use of " in the question. Normally, a second set of double-quotes would close the question being asked in the dialogue box. Remember, we opened the question with double quotes: 

var answer = confirm("Do you...

The preceding backslash prevents the JavaScript interpreter from parsing the quotes and instead includes them in the question.

OUTPUT:


More JavaScript Tutorials

JavaScript Disable Enter Key on Form Submission

View More...