Skip to content

JavaScript confirm dialog | Example code

  • by

You can use confirm() method to display a confirmation dialog in JavaScript. This method displays a dialog box with an optional message, an OK button, and a Cancel button.

confirm(message)
// OR
let result = window.confirm(question);

This method returns true if the user clicked “OK”, otherwise false.

JavaScript confirm dialog

Simple example code Display a confirmation box, and output what the user clicked:

<!DOCTYPE html>
<html>
<body>
  <script>
    function myFunction() {
      let text;
      if (confirm("Press a button!") == true) {
        text = "You pressed OK!";
      } else {
        text = "You canceled!";
      }
      console.log(text);
    }
  </script>
</body>
</html>

Output:

JavaScript confirm dialog

More code

if (window.confirm("Do you really want to leave?")) {
  window.open("exit.html", "Thanks for Visiting!");
}

Do comment if you have any doubts or suggestions on this JS dialog topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading