Tuesday, May 28, 2024

Using confirm() in JavaScript

   
confirm() in JavaScript

JavaScript confirm() Method

The confirm() method in JavaScript is used to get confirmation from the user. It displays a popup box with a specified message and two buttons: "OK" and "Cancel." If the user clicks "OK," the method returns true; if the user clicks "Cancel," it returns false.

The confirm() method is useful for confirming actions like deletions, form submissions, or any critical operations that require user confirmation.

Syntax for confirm()

confirm('Message goes here');

Example Usage

You can also use the confirm() method within conditional statements to handle different responses from the user. Here’s an example of how to use confirm() in an if statement:

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript">
    function myConfirm() {
      var con = confirm("Click either the OK or Cancel button");
      if (con === true) {
        alert("You clicked the OK button");
      } else {
        alert("You clicked the Cancel button");
      }
    }
  </script>
</head>
<body>
  <input onclick="myConfirm()" type="button" value="Try this" />
</body>
</html>

Explanation

HTML Structure: The basic HTML structure includes the <head> and <body> tags. Inside the <head>, we include a <script> tag where we define our JavaScript function.

JavaScript Function: The function myConfirm() uses the confirm() method to display a confirmation dialog. Depending on the user's response, it shows an alert with a different message.

Event Handling: The button in the HTML calls the myConfirm() function when clicked, demonstrating how the confirm() method works in a real scenario.

By using the confirm() method, you can effectively interact with users and get their confirmation for critical operations on your web pages.

No comments:

Post a Comment