/  Technology   /  JavaScript Confirm

JavaScript Confirm

 

In JavaScript, the confirm method invokes a function that prompts the user for confirmation of a particular action. Confirm () invokes a dialogue with a question and two options, OK and Cancel, using a window object. By selecting the OK option, the function will be executed; by selecting the Cancel option, the block code will be aborted.

It returns true if the user selects the OK option; otherwise, it returns false.

Syntax:

confirm("Select an Option!");  

Parameters:

A “message” value in string format is required to display in the confirmation dialog box.

Return value:

If the OK option is selected, the confirm method returns a Boolean output, either true or false.

The boolean value indicates whether OK (true) or Cancel (false) was selected. The returned value is always false if a browser ignores in-page dialogues.

Usage of the Confirm method

  • JavaScript confirm() displays a specific message on a dialog box with OK and Cancel options for the user to confirm the action.
  • Some CRUD operations require the use of a confirmation message rather than the direct application of an action.
  • This is a method of accepting or verifying something.
  • As a result, the browser is forced to read the message and focus on the current window.
  • Until the confirmation window is closed, all actions are halted.
  • If the user selects OK, it returns true. If the user selects CANCEL, it returns false.

Example

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Click the button to invoke the confirm().</p>
<button onclick="myFunction()">Click Here</button>
<p id="conf"></p>
<script>
function myFunction() {
var result;
var r = confirm("Select an Action!");
if (r == true) {
result = "You have select The OK!";
} else {
result = "You have select The Cancelled!";
}
document.getElementById("conf").innerHTML = result;
}
</script>
</body>
</html>

OUTPUT : 

As shown in the above html page, some text and an action button will be displayed as follows:

Clicking the Click Here button will display a dialogue box with the specified message as well as options for OK and Cancel.

If we select the OK action, the code true block code will be executed; otherwise, the false block code will be executed. Take a look at the following output:

 

Leave a comment