Show a confirmation popup in javascript​

problem

You’re creating a dynamic web page that asks the user for a confirmation. For example let’s imagine a user interface with a table of items that you can edit or delete each one. Before deleting an item, you wish to double check with the user if they’re sure to proceed with taking this action. By using JavaScript, we can accomplish this piece of logic.

solution

JavaScript comes out of the box with a function for showing a confirmation popup. It is the confirm() function as shown below in an example.

				
					function confirm_popup()
{
     let response = confirm("Do you accept?"); 
     if (response == true)
     {
        console.log("ok");
     }else {
        console.log("no");
    }
}
				
			

The confirm function returns a Boolean value that is either True or False. If it’s True the code above print in the console of JS the message “ok” or “no” respectively.

In order to execute the piece of JavaScript above, let’s put it in an HTML file that will have a button and call that function when it’s clicked. The code is shown below:

				
					<html>
   <head>
      <script type="text/javascript">
         function confirm_popup()
         {
            let response = confirm("Do you accept?"); 
            if (response == true)
            {
               console.log("ok");
            }else {
               console.log("no");
            }
         }
   </script>   
   </head>
   <body>
      <input type="button" value="confirm" onclick="confirm_popup()"/>
   <script>var rocket_beacon_data = {"ajax_url":"https:\/\/programmerabroad.com\/wp-admin\/admin-ajax.php","nonce":"e170fbea81","url":"https:\/\/programmerabroad.com\/show-a-confirmation-popup-in-javascript","is_mobile":false,"width_threshold":1600,"height_threshold":700,"delay":500,"debug":null,"status":{"lrc":true},"lrc_threshold":1800}</script><script data-name="wpr-wpr-beacon" src='https://programmerabroad.com/wp-content/plugins/wp-rocket/assets/js/wpr-beacon.min.js' async></script></body>
</html>


				
			

output

Open the page in a web browser and click on the confirm button. It should show the popup like below:

Now, open the web developer tools of your browser and navigate to the console. Depending on the user response from the popup, it should show the message ok or no

JavaScript clicking on the onfirm popup outputs in console

conclusion

Simply in JavaScript we can use the confirm function to show a default pop up for confirmation. There are better ways for showing more user friendly popups but this is one of the simplest. You can see it live by clicking below:

see it live

Share it!

Facebook
Twitter
LinkedIn
Reddit
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x