Skip to content

Confirm box in JavaScript | Example code

  • by

JavaScript Confirm box is used to verify or accept something. Use confirm() method to display the Confirm box in JavaScript. This method returns true if the user clicks “OK”, otherwise false.

confirm(message)
// code
confirm("Press a button!\nEither OK or Cancel.");

Confirm box in JavaScript

A simple example code display confirms dialog box with a message, an OK button, and a Cancel button.

<!DOCTYPE html>
<html>
<head>
  <body>
    <script>

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

</body>
</html>

Output:

Confirm box in JavaScript

How to create a dialog with “OK” and “Cancel” options?

Answer: Use confirm() method, that displays a prompt and returns true or false based on what the user decided. This is the easiest way to achieve that functionality.

if (confirm('Are you sure you want to save this thing into the database?')) {
  // Save it!
  console.log('Thing was saved to the database.');
} else {
  // Do nothing!
  console.log('Thing was not saved to the database.');
}

Do comment if you have any doubts or suggestions on this Js basic topic.

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

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

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

Continue reading