Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

How to use window.confirm in JavaScript?

Get support on JavaScript,jQuery, AJAX and other related technology.
Post Reply
admin
Site Admin
Posts: 45

How to use window.confirm in JavaScript?

Post by admin » Sun Oct 20, 2019 1:37 am

The window.confirm() method displays a modal dialog with an optional message and two buttons, OK and Cancel.
Now, let's take the following example:

Code: Select all

result = window.confirm(message);
Here, message is the optional string to be displayed in the dialog and result is a boolean value indicating whether OK or Cancel was selected (true means OK).

window.confirm() is typically used to ask for user confirmation before doing a dangerous operation like deleting something in a Control Panel:

Code: Select all

if(window.confirm("Are you sure you want to delete this?")) {
 deleteItem(itemId);
}
The output of that code would look like this in the browser:
Image
If you need it for later use, you can simply store the result of the user's interaction in a variable:

Code: Select all

var deleteConfirm = window.confirm("Are you sure you want to delete this?");
Notes
  • The argument is optional and not required by the specification.
  • Dialog boxes are modal windows - they prevent the user from accessing the rest of the program's interface until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box (or modal window). And regardless, there are very good reasons to avoid using dialog boxes for confirmation.
  • Starting with Chrome 46.0 this method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modal.
  • It is commonly accepted to call the confirm method with the window notation removed as the window object is always implicit. However, it is recommended to explicitly define the window object as expected behavior may change due to implementation at a lower scope level with similarly named methods

Post Reply