Alert boxes and confirmation boxes

Alert boxes are used to communicate messages to the user without taking them away from a web page. They are highly visible and must be acknowledged by clicking on ‘OK’ before the user can continue interacting with the web page.

Confirmation boxes also display a message but they give two options to the user: ‘OK’ and ‘Cancel’. Using JavaScript, you can program what will happen depending on which option the user chooses.

Alert boxes can tell the user that they have not completed a form correctly, and confirmation boxes can be used to ask the user to confirm something eg. you could ask the user if they accept terms and conditions of your site. If they click on OK, they can continue using the site, but if they click on Cancel then they will be redirected to another page.

Alert boxes and confirmation boxes can be annoying for the user so they should only be used when absolutely necessary. Watch the video below which explains both alert and confirmation boxes, and then scroll down to see the sample code for each type.

Here is the code for alert boxes:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>Alert boxes</title>
 
</head>
<body>
 
 <script type="text/javascript">
 
 // This is an alert box which can be used to display messages in a popup window
 // It can be very annoying for users so use only when necessary
 // Alert boxes can be used to warn a user that they haven't completed a form properly
 alert("I am an alert box!");
 
 
 </script>
 
</body
</html>

Here is the code for confirmation boxes:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>Confirmation boxes</title>
 
</head>
<body>
 
 <script type="text/javascript">
 
 // This is a confirmation box which gives two options: OK, and Cancel.
 var r=confirm("Press a button");
 if (r==true) {
 x = "You pressed OK!";
 } else {
 x = "You pressed Cancel!";
 }
 document.write(x); 
 
 
 </script>
 
</body
</html>

Next tutorial: JavaScript prompts (user input boxes)