confirm() displays a modal dialog with OK and Cancel. It returns true for OK and false for Cancel.
const accepted = confirm("Are you sure?");Use the returned Boolean with an if/else condition. This is the same idea as the original tutorial, expressed with clearer variable names.
const accepted = confirm("Are you sure?");
if (accepted) {
// Continue with the action.
} else {
// Cancel or leave the page unchanged.
}The original demo links the confirm result to an alert window. That facility remains available.
const accepted = confirm("Are you satisfied with the quality of the tutorials here?");
if (accepted) {
alert("Thank you");
} else {
alert("Please use the contact us page to give your feedback");
}<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Confirm demo</title></head>
<body>
<button id="confirmButton" type="button">Click here to display confirm window</button>
<script>
document.getElementById("confirmButton").addEventListener("click", () => {
const accepted = confirm("Are you satisfied with the quality of the tutorials here?");
alert(accepted ? "Thank you" : "Please use the contact us page to give your feedback");
});
</script>
</body>
</html>The original tutorial includes a second demo that replaces the current document with document.write(). That historical demo is preserved at the same URL, but document.write() is not recommended for normal page output because it can replace the document.
DEMO of window confirm using document.write()
function show_confirm() {
const accepted = confirm("Are you sure?");
if (accepted) {
document.write("You clicked OK");
} else {
document.write("You clicked Cancel");
}
document.write('<br><br>Back to <a href="window-confirm-demo2.php">Demo Page</a>');
document.write('<br><br>Back to <a href="window-confirm.php">Window Confirm Page</a>');
}document.getElementById("confirmButton").addEventListener("click", () => {
const accepted = confirm("Are you sure?");
document.getElementById("result").textContent = accepted ? "You clicked OK" : "You clicked Cancel";
});Confirmation is commonly used before a destructive operation. The original example redirects to another page and includes a record ID in the query string after confirmation. See also the redirect tutorial.
function show_confirm(c_id) {
const accepted = confirm("Are you sure you want to delete?");
if (accepted) {
window.location.href = `list.php?todo=del&c_id=${encodeURIComponent(c_id)}`;
}
}<button type="button" onclick="show_confirm(2)">Delete</button>Window object Reference Window close Passing data from Child window to parent window
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.