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

The JavaScript confirm() method is used to verify the user activity regarding the confirm() popup or dialog box. For example:

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 do press either OK or Cancel button. Then JavaScript writes the text based on the button you've clicked. It is used to ask from user about something, to proceed further, based on their choice, in this general form/way:

<!DOCTYPE html>
<html>
<body>

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

Note - The confirm() is same as window.confirm(). It is because, window is a global object. And in JavaScript, a method by default belongs to the window object.

JavaScript confirm() Syntax

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

confirm(message)

The confirm() method returns true if user clicks on OK, otherwise returns false.

JavaScript Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋