How to Create a Yes/No Confirmation Box in JavaScript
Table of Contents
Sometimes, you just want an easy way to get a yes or no response from the user in the browser.
In this post, we'll be learning how to create a yes/no confirmation box in JavaScript to get that response from the user.
confirm()
The best way to create a yes/no confirmation box is to use the JavaScript confirm()
function. This function will make the browser render a dialog box with a message and two buttons, an Ok
and a Cancel
button.
When the user interacts with this dialog box, it will return to you a boolean, true
if the user clicked the Ok
button and false
if the user clicked the Cancel
button.
Here's how to create a confirmation box using confirm()
:
JAVASCRIPTconst response = confirm("Are you sure you want to do that?");
console.log(response);
Here's how the code above would look in the browser:
Confirmation box in the browser
This is how a full HTML page using this code would look like:
HTML<!DOCTYPE html>
<html>
<head>
<title>JavaScript Yes/No Confirmation box</title>
<script>
const confirmAction = () => {
const response = confirm("Are you sure you want to do that?");
if (response) {
alert("Ok was pressed");
} else {
alert("Cancel was pressed");
}
}
</script>
</head>
<body>
<button onclick="confirmAction()">
Perform action
</button>
</body>
</html>
As a recap, after you get the response from the user, you can do something with it:
JAVASCRIPTconst response = confirm("Are you sure you want to do that?");
if (response) {
// add code if the user pressed the Ok button
console.log("Ok was pressed");
} else {
// add code if the user pressed the Cancel button
console.log("Cancel was pressed");
}
With that, you've created a yes/no confirmation box in JavaScript.
Conclusion
In this post, we've seen how to create a yes/no confirmation box in JavaScript to get that response from the user.
From there, you can do whatever you need to do with that response.
Hopefully, this helped you out. Happy coding!
- Managing PHP Dependencies with Composer
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- Getting Started with Deno
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js