Javascript Window confirm() Method (original) (raw)
Last Updated : 20 Aug, 2024
The confirm()
method in JavaScript displays a dialog box with a message and two buttons: OK and Cancel. It is often used to get user confirmation before an action, returning true if OK is clicked, and false if Cancel is clicked.
**Syntax
confirm(message);
**Parameters
- **message: It is the optional string to be displayed in the dialog. It returns a boolean value indicating whether OK or Cancel was selected (true means OK and false means that the user clicked cancel).
**Example 1: Basic Confirmation Dialog
In this example the window.confirm() method displays a dialog box with "OK" and "Cancel" options. It returns true if "OK" is clicked and false for "Cancel," allowing conditional actions based on user response.
HTML `
Window confirm() MethodGeeksforGeeks
Window confirm() Method
Click the button to display a confirm box.
<button onclick="geek()">
Click me!
</button>
<script>
function geek() {
let result = confirm("Press OK to close this option");
if (result === true) {
document.getElementById("add").textContent =
"User clicked OK";
console.log("User clicked OK");
} else {
document.getElementById("add").textContent =
"User clicked Cancel";
console.log("User clicked Cancel");
}
}
</script>
`
**Output:
Example 2: Confirmation Dialog on Link Click
In this example The window.confirm() method displays a confirmation dialog when a user clicks the link. Returning true allows navigation; false cancels it, preventing the link from opening based on the user's choice.
HTML `
<h2>JavaScript confirm() Example with a Link</h2>
<a href="https://www.geeksforgeeks.org"
onclick="return confirmLinkClick()">
Click this link
</a>
<script>
function confirmLinkClick() {
return confirm("Are you sure you want to navigate away?");
}
</script>
`
**Output: