A JavaScript confirm
function is a convenient way to display the confirmation box with
the “OK” and “Cancel” options and capture user’s response. Let’s see how it’s done.
To display the confirmation dialog with JavaScript, you can call the function confirm
passing in your question as a first argument.
confirm("Press OK to confirm");
The window confirm
function returns boolean, which describes user’s response.
Let’s create a variable, capture the response of the user and log it to the console.
let isConfirmed = confirm("Press OK to confirm");
console.log(isConfirmed);
You can also create a button that displays the confirmation modal once clicked.
<body>
<script>
function ask() {
let isConfirmed = confirm("Press OK to confirm");
console.log(isConfirmed);
}
</script>
<button onClick="ask()">
Confirm?
</button>
</body>
In the example above I’ve added a few new things:
- I wrapped the confirmation code into a function
ask
- I’ve created a button with the text
Confirm?
- I’ve set the function
ask
to be theonClick
handler for the confirmation button