JavaScript: Create confirmation box with yes and no options

Learn how to create confirmation box with yes and no options with JavaScript

Posted on March 03, 2021


You can create a JavaScript confirmation box that offers “yes” and “no” options by using the confirm() method.

The confirm() method will display a dialog box with a custom message that you can specify as its parameter. The dialog will also have “OK” and “Cancel” buttons, which return the boolean value true or false.

Here’s an example:

let isExecuted = confirm("Are you sure to execute this action?");

console.log(isExecuted); // OK = true, Cancel = false

Please keep in mind that the confirm() method is part of the window object, which means you can only call it from the browser. You can test the confirm() method by simply opening your browser’s console and type in confirm() as in the screenshot below:

JavaScript confirmation dialog in the browser
JavaScript confirmation dialog in the browser

The following HTML page code will start the confirmation dialog when you click on the Delete button:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>JavaScript confirmation box</title>
    <script>
      // The function below will start the confirmation dialog
      function confirmAction() {
        let confirmAction = confirm("Are you sure to execute this action?");
        if (confirmAction) {
          alert("Action successfully executed");
        } else {
          alert("Action canceled");
        }
      }
    </script>
  </head>
  <body>
    <h1>Call the confirmation box</h1>
    <button onclick="confirmAction()">Delete</button>
  </body>
</html>

You need to place the code you wish to run from the result of the confirmation dialog inside the if/else code block:

if (confirmAction) {
  // if true
  alert("Action successfully executed");
} else {
  // if false
  alert("Action canceled");
}

And that’s how you can create a confirmation dialog with JavaScript.

Related articles:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more