Skip to content

JavaScript prompt Yes No

  • by

JavaScript prompt Yes No option is not available in the prompt method. You can use the confirm() method to display a dialog box with a message, an OK button, and a Cancel button. It returns true if the user clicked “OK”, otherwise false.

confirm(message)

Note: the message is optional.

You can use jQuery UI Dialog.

These libraries create HTML elements that look and behave like a dialog box, allowing you to put anything you want (including form elements or video) in the dialog.

JavaScript prompt Yes No

Simple example code.

<!DOCTYPE html>
<html>
<body>

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

Output:

JavaScript prompt Yes No

See the complete code: JavaScript confirmation with yes and no buttons

https://codepen.io/nathansebhastian/pen/MWVKJeW

<head>
  <style>
  html,
  body {
    height: 100%;
  }
  .overlay {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.8);
    z-index: 2;
  }

  .confirm-box {
    position: absolute;
    width: 50%;
    height: 50%;
    top: 25%;
    left: 25%;
    text-align: center;
    background: white;
  }

  .close {
    cursor: pointer;
  }
</style>
</head>
<body>
  <div class="overlay" id="overlay" hidden>
    <div class="confirm-box">
      <div onclick="closeConfirmBox()" class="close">&#10006;</div>
      <h2>Confirmation</h2>
      <p>Are you sure to execute this action?</p>
      <button onclick="isConfirm(true)">Yes</button>
      <button onclick="isConfirm(false)">No</button>
    </div>
  </div>
  <button onclick="showConfirmBox()">Delete</button>
  <p>Full tutorial here: <a href="">JavaScript - Create confirmation box with yes and no options</a></p>
  <script>
  function showConfirmBox() {
    document.getElementById("overlay").hidden = false;
  }
  function closeConfirmBox() {
    document.getElementById("overlay").hidden = true;
  }

  function isConfirm(answer) {
    if (answer) {
      alert("Answer is yes");
    } else {
      alert("Answer is no");
    }
    closeConfirmBox();
  }
</script>
</body>

Do comment if you have any doubts or suggestions on this Js prompt 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

Your email address will not be published. Required fields are marked *