JavaScript confirm()/window.confirm(): Confirm Dialog Box

Are you sick of wondering if your website visitors intended to take that action or if they accidentally clicked the wrong button? Do you want to make it easy for users to confirm their selections before proceeding? Look no further than JavaScript's confirm() function!

You can create a popup window that asks the user to confirm or cancel their action with just a few lines of code, giving them the opportunity to double-check their decision and avoid mistakes. So let's start with a brief definition.

The JavaScript confirm() method is used to verify the user's activity regarding the confirm() popup or dialog box.

JavaScript confirm() syntax

The syntax of the confirm() method in JavaScript is:

confirm(message)

The confirm() method returns true if the user clicks OK; otherwise, it returns false.

JavaScript confirm() example

Consider the following code as an example demonstrating the confirm() function in JavaScript:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <h2>The confirm() Method</h2>
   <button onclick="myFunction()">Click Me</button>
   <p id="myP"></p>
   <script>
      function myFunction() {
         var msg;
         x = confirm("Press OK or Cancel button.");
         if(x==true) {
            msg = "You pressed OK button";
         }
         else {
            msg = "You pressed Cancel button";
         }
         document.getElementById("myP").innerHTML = msg;
      }
   </script>
   
</body>
</html>
Output

The confirm() Method

Click on the Click Me button, then press either the OK or Cancel button. Then JavaScript writes the text based on the button you've clicked. It is used to ask the user about something and then proceed further based on their choice in this general way:

<!DOCTYPE html>
<html>
<body>

   <button onclick="myFunction()">Ask</button>
   <script>
      function myFunction() {
         if(confirm("Press OK or Cancel button.")) {
            // If the user is OK with your confirmation box, do some work here
         }
         else {
            // Do some work here as an alternative to OK
         }
      }
   </script>
   
</body>
</html>

It should be noted that the confirm() function is the same as window.confirm(). It is because window is a global object. And in JavaScript, a method by default belongs to the window object.

Advantages of the confirm() function in JavaScript

Disadvantages of the confirm() function in JavaScript

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!