Confirmation Box with Yes or No button in JavaScript

In this article, we will see how to create confirmation box with Yes Or No using JavaScript.

In JavaScript, we can use the confirm() method of the window object to display a dialog / alert box.

The confirm() method is use to display a dialog box with custom text/ message that we can pass as an argument with the method.


confirm("Your custom message")

The dialog box also provide us with OK and Cancel button. And if the user click OK, it will return true, else it will return false if user click Cancel.

Confirmation Box with Ok and Cancel button

Lets see with an example on how to create confirmation box using JavaScript:

    click the button to open dialog Box
  <button onclick="openDialog()">Click Here</button>
  <script src="main.js"></script>

In script code:

function openDialog() {
  let customMsg = "Do you want Tea?";

  if (confirm(customMsg)) {
    console.log("User clicked OK");
  } else {
    console.log("User Clicked CANCEL");

In the code, we have use the if...else statement to display some message on our console, depending on the boolean results.


Yes/No instead of Ok/Cancel for Confirm in JavaScript

One of the drawback with confirm() method is that the dialog box is not a part of the website UI. So we cannot change the OK and Cancel button on the confirmation dialog box.

So we have to code our HTML confirmation box with Yes and No buttons and create our own function which will check if a user have click the yes button or the No button.

    <button onclick="showConfirmBox()">Show Dialog</button>
    <div id="confirm-box" hidden>
      <p>Do you really want to reset the database?</p>
      <button onclick="confirm('yes')">Yes</button>
      <button onclick="confirm('no')">No</button>

Script code:

function showConfirmBox() {
  document.getElementById("confirm-box").hidden = false;

function confirm(data) {
  if (data === "yes") {
    console.log(" user clicked yes");
  } else {
    console.log("user clicked No");

In the Html code, we have kept the div with id "confirm-box" hidden at first. And when we click the button Show Box, it's hidden property is set to true and the confirmation box is displayed on the screen.

The box have Yes and No button with an onclick event. When any button is clicked, the confirm() function checks if the user have clicked yes or no , depending on the argument that is passed.


Related Topics:

Check If A HTML Checkbox Is Checked Using JavaScript

Change Text Color Using JavaScript With Example

Copy Text From An HTML Element To Clipboard-JavaScript

Enable Or Disable Button Programmatically Using JavaScript

💾 Recommended Articles