855

I am going to make a button to take an action and save the data into a database.

Once the user clicks on the button, I want a JavaScript alert to offer “yes” and “cancel” options. If the user selects “yes”, the data will be inserted into the database, otherwise no action will be taken.

How do I display such a dialog?

matteo
  • 2,934
  • 7
  • 44
  • 59
crchin
  • 9,473
  • 6
  • 22
  • 28

17 Answers17

1596

You’re probably looking for confirm(), which displays a prompt and returns true or false based on what the user decided:

if (confirm('Are you sure you want to save this thing into the database?')) {
  // Save it!
  console.log('Thing was saved to the database.');
} else {
  // Do nothing!
  console.log('Thing was not saved to the database.');
}
Edric
  • 24,639
  • 13
  • 81
  • 91
s4y
  • 50,525
  • 12
  • 70
  • 98
  • 164
    confirm has OK and CANCEL buttons. Can these buttons be set to YES/NO? – Owen Apr 19 '13 at 00:20
  • 22
    @Owen No. [The spec](http://www.w3.org/html/wg/drafts/html/master/webappapis.html#simple-dialogs) says that you just get to provide a message. You can emulate a dialog in HTML (though it won't block like the built-in one). [jQuery Dialog](http://jqueryui.com/dialog/#modal-confirmation) is a good example of implementing this kind of thing. – s4y Apr 19 '13 at 17:00
  • 5
    note: you can put a `return` inside the else and then you don't need to wrap all of your code in the confirm! (case by case fix though) – Jacob Raccuia Sep 02 '14 at 14:54
  • 28
    @JacobRaccuia Or simply `if(!confirm('message')) return;` – Aaron Oct 15 '14 at 21:03
  • @JacobRaccuia you're missing a 'false' after the return, otherwise it will submit regardless of what you click on the confirm box. – silvenwolf Feb 22 '17 at 17:40
  • 8
    When using `confirm` in React, I had to use `window.confirm` to avoid an `Unexpected use of confirm` error – sebtheiler Nov 17 '20 at 13:26
  • 1
    this is not an answer to the question, was about "YES / NO", not "OK / CANCEL", misleads and because of it it's harder to find a proper answer – Flash Thunder Nov 24 '20 at 14:43
150
var answer = window.confirm("Save data?");
if (answer) {
    //some code
}
else {
    //some code
}

Use window.confirm instead of alert. This is the easiest way to achieve that functionality.

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
97

How to do this using 'inline' JavaScript:

<form action="http://www.google.com/search">
  <input type="text" name="q" />
  <input type="submit" value="Go"
    onclick="return confirm('Are you sure you want to search Google?')"
  />
</form>
dana
  • 17,267
  • 6
  • 64
  • 88
  • 9
    It's better to handle onsubmit event of the form: with your code, if user presses enter in text, the form gets submitted without any request! – p91paul Jun 03 '13 at 13:58
  • 1
    @p91paul - Which browser does this fail for you? I just tried pressing enter in IE, Chrome, and Safari on Windows and it worked as expected. http://jsfiddle.net/ALjge/1/ – dana Jun 03 '13 at 16:24
  • 1
    well, I was sure of what I was saying, but I haven't tested and I was wrong. sorry! – p91paul Jun 03 '13 at 21:41
  • 1
    No problem :) There is usually more than one way to skin a cat. I just wanted to confirm my approach was working. Using the `
    ` as you suggested works too :)
    – dana Jun 04 '13 at 02:08
48

Avoid inline JavaScript - changing the behaviour would mean editing every instance of the code, and it isn’t pretty!

A much cleaner way is to use a data attribute on the element, such as data-confirm="Your message here". My code below supports the following actions, including dynamically-generated elements:

  • a and button clicks
  • form submits
  • option selects

jQuery:

$(document).on('click', ':not(form)[data-confirm]', function(e){
    if(!confirm($(this).data('confirm'))){
        e.stopImmediatePropagation();
        e.preventDefault();
    }
});

$(document).on('submit', 'form[data-confirm]', function(e){
    if(!confirm($(this).data('confirm'))){
        e.stopImmediatePropagation();
        e.preventDefault();
    }
});

$(document).on('input', 'select', function(e){
    var msg = $(this).children('option:selected').data('confirm');
    if(msg != undefined && !confirm(msg)){
        $(this)[0].selectedIndex = 0;
    }
});

HTML:

<!-- hyperlink example -->
<a href="http://www.example.com" data-confirm="Are you sure you want to load this URL?">Anchor</a>

<!-- button example -->
<button type="button" data-confirm="Are you sure you want to click the button?">Button</button>

<!-- form example -->
<form action="http://www.example.com" data-confirm="Are you sure you want to submit the form?">
    <button type="submit">Submit</button>
</form>

<!-- select option example -->
<select>
    <option>Select an option:</option>
    <option data-confirm="Are you want to select this option?">Here</option>
</select>

JSFiddle demo

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rybo111
  • 12,240
  • 4
  • 61
  • 70
  • 2
    Very clean solution I haven't thought of before. Can be even more concise though: `$("[data-confirm]").on('click,submit', function() { /* ... */ })` – Grimace of Despair Aug 22 '13 at 08:38
  • 1
    Sorry, couldn't resist to have a look at it again. First: the events should be separated by a space. Second: you can still tighten the code http://jsfiddle.net/jguEg/ ;) – Grimace of Despair Aug 22 '13 at 12:27
  • @GrimaceofDespair I have updated the code, because clicking and confirming a `type="button"` then asked if the user wanted to submit the form (because you are clicking a form element), which obviously didn't happen after clicking OK again. – rybo111 Mar 29 '14 at 14:31
  • 1
    These are good examples, though they all use the confirm() dialog so you can't rename the Cancel/OK buttons :| – rogerdpack Nov 01 '16 at 16:05
  • @rogerdpack Yes, but the beauty of using data attributes is you can change `confirm()` to whatever you want without changing the HTML. – rybo111 Nov 01 '16 at 16:12
39

You have to create a custom confirmBox. It is not possible to change the buttons in the dialog displayed by the confirm function.

jQuery confirmBox


function doConfirm(msg, yesFn, noFn)
{
    var confirmBox = $("#confirmBox");
    confirmBox.find(".message").text(msg);
    confirmBox.find(".yes,.no").unbind().click(function()
    {
        confirmBox.hide();
    });
    confirmBox.find(".yes").click(yesFn);
    confirmBox.find(".no").click(noFn);
    confirmBox.show();
}

doConfirm("Are you sure?", function yes()
{
    alert('Yes');
}, function no()
{
    alert('No');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="confirmBox">
    <div class="message"></div>
    <span class="yes">Yes</span>
    <span class="no">No</span>
</div>

Pure JavaScript confirmBox


    function doSomething(){
        document.getElementById('id_confrmdiv').style.display="block"; //this is the replace of this line

        document.getElementById('id_truebtn').onclick = function(){
           // Do your delete operation
            alert('true');
        };
        document.getElementById('id_falsebtn').onclick = function(){
             alert('false');
           return false;
        };
    }
body { font-family: sans-serif; }

#id_confrmdiv
{
    display: none;
    background-color: #eee;
    border-radius: 5px;
    border: 1px solid #aaa;
    position: fixed;
    width: 300px;
    left: 50%;
    margin-left: -150px;
    padding: 6px 8px 8px;
    box-sizing: border-box;
    text-align: center;
}

#id_confrmdiv button {
    background-color: #ccc;
    display: inline-block;
    border-radius: 3px;
    border: 1px solid #aaa;
    padding: 2px;
    text-align: center;
    width: 80px;
    cursor: pointer;
}

#id_confrmdiv .button:hover
{
    background-color: #ddd;
}

#confirmBox .message
{
    text-align: left;
    margin-bottom: 8px;
}
<div id="id_confrmdiv">confirmation
    <button id="id_truebtn">Yes</button>
    <button id="id_falsebtn">No</button>
</div>

<button onclick="doSomething()">submit</button>
Asons
  • 84,923
  • 12
  • 110
  • 165
Keval Bhatt
  • 6,224
  • 2
  • 24
  • 40
  • 2
    So nice too.. pretty simple, pure javascript and not so much css. Like it :D – m3nda Aug 03 '15 at 10:56
  • Confirm boxes should disappear once an item is pressed. Also, you should use classes, not IDs. – rybo111 Dec 27 '15 at 11:47
  • @rogerdpack I updated fiddle let me know if need anything from my side :) – Keval Bhatt Oct 20 '16 at 06:24
  • @rogerdpack if you Like answer then you can up vote :P – Keval Bhatt Oct 21 '16 at 09:33
  • @KevalBhatt, I like your 'pure JS' version. Is there any way to remove/hide/whatever dialog right after hitting a button? If I put `document.getElementById('id_confrmdiv').style.display="none";` the dialog is hidden after all commands executed in method for a button. – Andrii Muzychuk Jan 27 '17 at 15:01
  • @AndriiMuzychuk, yes you can do that. – Keval Bhatt Feb 13 '17 at 06:04
  • @KevalBhatt I like this, it is about as simple as it gets. But it seems like you didn't update your fiddle to make the confirmation dialog disappear... or to use classes instead of IDs. Also, just to make clear, although you have the buttons in the confirmation dialog calling `alert` (bad!), in fact your simple solution here shows how to **avoid** doing that! – mike rodent Jul 12 '20 at 11:56
  • 2
    Guys, you got pretty good examples, this is a POC. If you don't like it , adapt to your needs and do not blame author. Note: jquery confirmBox example link is not working anymore. By the way, Pure JS is great example. – m3nda Aug 04 '21 at 08:18
  • This has the advantage over "confirm" that you can have more than 2 buttons, or even arbitrary HTML. Potential downside is that it is non-modal. Maybe it could be made to be modal?

    I agree with m3nda. Proof of concepts should be as simple as possible to convey the main concept. Enhance as required for your specific needs.
    – user1062589 Nov 01 '21 at 12:46
  • Link is broken this is why you should use SO code snippets please. – Blackbam Jul 25 '23 at 12:20
  • @Blackbam -- Yes, was my early days when I didn't know about snippets :) ... I've updated it now, thanks for letting me know. – Asons Jul 26 '23 at 05:49
17

Or simply:

<a href="https://some-link.com/" onclick="return confirm('Are you sure you want to go to that link?');">click me!</a>
Edric
  • 24,639
  • 13
  • 81
  • 91
JavaRunner
  • 2,455
  • 5
  • 38
  • 52
  • 1
    Thank you! I was afraid I'd have to include jQuery in my simple CRUD app just to do a simple are-you-sure-you-want-to-delete this. – Will Matheson Jun 06 '19 at 18:41
14

This plugin can help you jquery-confirm easy to use

$.confirm({
    title: 'Confirm!',
    content: 'Simple confirm!',
    confirm: function(){
        alert('Confirmed!');
    },
    cancel: function(){
        alert('Canceled!')
    }
});
swen
  • 29
  • 4
ibrahim ozboluk
  • 421
  • 5
  • 10
9

This a full responsive solution using vanilla javascript :

// Call function when show dialog btn is clicked
document.getElementById("btn-show-dialog").onclick = function(){show_dialog()};
var overlayme = document.getElementById("dialog-container");

function show_dialog() {
 /* A function to show the dialog window */
    overlayme.style.display = "block";
}

// If confirm btn is clicked , the function confim() is executed
document.getElementById("confirm").onclick = function(){confirm()};
function confirm() {
 /* code executed if confirm is clicked */   
    overlayme.style.display = "none";
}

// If cancel btn is clicked , the function cancel() is executed
document.getElementById("cancel").onclick = function(){cancel()};
function cancel() {
 /* code executed if cancel is clicked */  
    overlayme.style.display = "none";
}
.popup {
  width: 80%;
  padding: 15px;
  left: 0;
  margin-left: 5%;
  border: 1px solid rgb(1,82,73);
  border-radius: 10px;
  color: rgb(1,82,73);
  background: white;
  position: absolute;
  top: 15%;
  box-shadow: 5px 5px 5px #000;
  z-index: 10001;
  font-weight: 700;
  text-align: center;
}

.overlay {
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,.85);
  z-index: 10000;
  display :none;
}

@media (min-width: 768px) {
  .popup {
    width: 66.66666666%;
    margin-left: 16.666666%;
  }
}
@media (min-width: 992px) {
  .popup {
    width: 80%;
    margin-left: 25%;
  }
}
@media (min-width: 1200px) {
  .popup {
    width: 33.33333%;
    margin-left: 33.33333%;
  }
}

.dialog-btn {
  background-color:#44B78B;
  color: white;
  font-weight: 700;
  border: 1px solid #44B78B;
  border-radius: 10px;
  height: 30px;
  width: 30%;
}
.dialog-btn:hover {
  background-color:#015249;
  cursor: pointer;
}
<div id="content_1" class="content_dialog">
    <p>Lorem ipsum dolor sit amet. Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit.</p>
    <p>Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit. Nullam felis tellus, tristique nec egestas in, luctus sed diam. Suspendisse potenti.</p>
</div>

<button id="btn-show-dialog">Ok</button>


<div class="overlay" id="dialog-container">
  <div class="popup">
    <p>This will be saved. Continue ?</p>
    <div class="text-right">
      <button class="dialog-btn btn-cancel" id="cancel">Cancel</button>
      <button class="dialog-btn btn-primary" id="confirm">Ok</button>
    </div>
  </div>
</div>
Alouani Younes
  • 948
  • 9
  • 17
9

You can intercept the onSubmit event using JavaScript.

Then call a confirmation alert and then grab the result.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
marcelo-ferraz
  • 3,147
  • 4
  • 38
  • 55
6

Another way to do this:

$("input[name='savedata']").click(function(e){
       var r = confirm("Are you sure you want to save now?");

       //cancel clicked : stop button default action 
       if (r === false) {
           return false;
        }

        //action continues, saves in database, no need for more code


   });
Aris
  • 4,643
  • 1
  • 41
  • 38
5

xdialog provides a simple API xdialog.confirm(). Code snippet is following. More demos can be found here

document.getElementById('test').addEventListener('click', test);

function test() {
  xdialog.confirm('Are you sure?', function() {
    // do work here if ok/yes selected...
    console.info('Done!');
  }, {
    style: 'width:420px;font-size:0.8rem;',
    buttons: {
      ok: 'yes text',
      cancel: 'no text'
    },
    oncancel: function() {
      console.warn('Cancelled!');
    }
  });
}
<link href="https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.js"></script>
<button id="test">test</button>
xia xiongjun
  • 141
  • 3
  • 6
  • You gotta describe what you mean by `// do work here..`. Do the functions for `YES TEXT` and `NO TEXT` go there? – kev May 06 '19 at 15:30
  • 1
    @kev, the callback will be executed when user select ok button. – xia xiongjun May 08 '19 at 01:24
  • and where does the logic for `NO TEXT` go? – kev May 08 '19 at 14:14
  • You can add an `oncancel` option to the last parameter options of `xdialog.confirm(text, onyes, options)`. For more details see: [xdialog default-options](https://xxjapp.github.io/xdialog/readme#default-options) – xia xiongjun May 10 '19 at 01:42
3

Made super simple, tiny vanilla js confirm dialog with Yes and No buttons.
It's a pity we can't customize the native one.

https://www.npmjs.com/package/yesno-dialog.

enter image description here

Alex Sidorenko
  • 546
  • 1
  • 3
  • 14
3

Another solution apart from the others is to use the new dialog element. You need to make use of show or showModal methods based on interactivity with other elements. close method can be used for closing the open dialog box.

<dialog>
  <button class="yes">Yes</button>
  <button class="no">No</button>
</dialog>

const dialogEl = document.querySelector("dialog");
const openDialog = document.querySelector("button.open-dialog");
const yesBtn = document.querySelector(".yes");
const noBtn = document.querySelector(".no");
const result = document.querySelector(".result");

openDialog.addEventListener("click", () => {
  dialogEl.showModal();
});

yesBtn.addEventListener("click", () => {
  // Below line can be replaced by your DB query
  result.textContent = "This could have been your DB query";
  dialogEl.close();
});

noBtn.addEventListener("click", () => {
  result.textContent = "";
  dialogEl.close();
});
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap');

body {
  font-family: "Roboto";
}

button {
  background: hsl(206deg 64% 51%);
  color: white;
  padding: 0.5em 1em;
  border: 0 none;
  cursor: pointer;
}

dialog {
  border: 0 none;
}

.result {
  margin-top: 1em;
}
<dialog>
  <button class="yes">Yes</button>
  <button class="no">No</button>
</dialog>
<button class="open-dialog">Click me</button>
<div class="result"></div>

Can I use?

Right now the compatibility is great with all the modern browsers.

m4n0
  • 29,823
  • 27
  • 76
  • 89
0

I'm currently working on a web workflow which already has it's own notifications/dialog boxes, and I recently (like, today) created a tiny, custom (and tailored to the project needs) YES/NO dialog box.

All dialog boxes appeard over a modal layer. Full user attention is required.

I define the options configurations in this way. This options are used to define the buttons text, and the values associated to each button when there clicked:

optionsConfig = [
   { text: 'Yes', value: true },
   { text: 'No', value: false }
]

The use of the function goes something like this:

const answer = await notifier.showDialog('choose an option', options.config);
if (answer) {
   // 'Yes' was clicked
} else {
   // 'No' was clicked!
}

What I do, it's simply creating a async event handler for each option, it means, there is a simple handler assigned to each button. Each handler returns the value of the option. The handlers are pushed inside an array. The array is then passed to Promise.race, and that is the return value of the showDialog method, which will correspond to the value's actual value (the one returned by the handler).

Can't provide too much code. As I said it's a very specific case, but the idea may be usefull for other implementations. Twenty lines of code or so.

Emilio Grisolía
  • 1,183
  • 1
  • 9
  • 16
0

A vanilla JavaScript option with a class for creating the custom modal dialog which includes a text box:

jsfiddle:

https://jsfiddle.net/craigdude/uh82mjtb/2/

html:

<!DOCTYPE html>
<html>


<style>
.modal_dialog
{
    box-sizing: border-box;
    background-color: #ededed;
    border-radius: 5px;
    border: 0.5px solid #ccc;
    font-family: sans-serif;    
    left: 30%;
    margin-left: -50px;
    padding: 15px 10px 10px 5px;
    position: fixed;
    text-align: center;
    width: 320px;
}

</style>

<script src="./CustomModalDialog.js"></script>

<script>
var gCustomModalDialog = null;


/** this could be static html from the page in an "invisible" state */
function generateDynamicCustomDialogHtml(){
    
    var html = "";
    html += '<div id="custom_modal_dialog" class="modal_dialog">';
    html += 'Name: <input id="name" placeholder="Name"></input><br><br>';
    html += '<button id="okay_button">OK</button>';
    html += '<button id="cancel_button">Cancel</button>';
    html += '</div>';
    return html;
}

function onModalDialogOkayPressed(event) {
    
    var name = document.getElementById("name");
    alert("Name entered: "+name.value);
}

function onModalDialogCancelPressed(event) {
    
    gCustomModalDialog.hide();
}

function setupCustomModalDialog() {

    var html = generateDynamicCustomDialogHtml();
    gCustomModalDialog = new CustomModalDialog(html, "okay_button", "cancel_button", 
            "modal_position", onModalDialogOkayPressed, onModalDialogCancelPressed);
}


function showCustomModalDialog() {
    
    if (! gCustomModalDialog) {
        setupCustomModalDialog();
    }
    gCustomModalDialog.show();  
    gCustomModalDialog.setFocus("name");
}


</script>

<body>

<button onclick="showCustomModalDialog(this)">Show Dialog</button><br>
Some content
<div id="modal_position">
</div>
Some additional content

</body>

</html>

CustomModalDialog.js:

/** Encapsulates a custom modal dialog in pure JS 
 */
class CustomModalDialog {
    
    /**
     * Constructs the modal content
     * @param htmlContent - content of the HTML dialog to show
     * @param okayControlElementId - elementId of the okay button, image or control
     * @param cancelControlElementId - elementId of the cancel button, image or control
     * @param insertionElementId - elementId of the <div> or whatever tag to 
     *            insert the html at within the document
     * @param callbackOnOkay - method to invoke when the okay button or control is clicked.
     * @param callbackOnCancel - method to invoke when the cancel button or control is clicked.
     * @param callbackTag (optional) - to allow object to be passed to the callbackOnOkay 
     *              or callbackOnCancel methods when they're invoked.
     */ 
    constructor(htmlContent, okayControlElementId, cancelControlElementId, insertionElementId,
                        callbackOnOkay, callbackOnCancel, callbackTag) { 

        this.htmlContent = htmlContent;
        this.okayControlElementId = okayControlElementId;               
        this.cancelControlElementId = cancelControlElementId;
        this.insertionElementId = insertionElementId;
        this.callbackOnOkay = callbackOnOkay;
        this.callbackOnCancel = callbackOnCancel;
        this.callbackTag = callbackTag;
    }


    /** shows the custom modal dialog */
    show() {
        // must insert the HTML into the page before searching for ok/cancel buttons
        var insertPoint = document.getElementById(this.insertionElementId);     
        insertPoint.innerHTML = this.htmlContent;
        
        var okayControl = document.getElementById(this.okayControlElementId);
        var cancelControl = document.getElementById(this.cancelControlElementId);

        okayControl.addEventListener('click', event => {
            this.callbackOnOkay(event, insertPoint, this.callbackTag);
        });
        cancelControl.addEventListener('click', event => {
            this.callbackOnCancel(event, insertPoint, this.callbackTag);
        });
    } // end: method    
    
    
    /** hide the custom modal dialog */
    hide() {
        var insertPoint = document.getElementById(this.insertionElementId);
        var okayControl = document.getElementById(this.okayControlElementId);
        var cancelControl = document.getElementById(this.cancelControlElementId);

        insertPoint.innerHTML = ""; 
        
        okayControl.removeEventListener('click',
            this.callbackOnOkay,
            false
        );
        cancelControl.removeEventListener('click',
            this.callbackOnCancel,
            false
        );
    } // end: method
    
    
    /** sets the focus to given element id 
     */
    setFocus(elementId) {
    
        var focusElement = document.getElementById(elementId);
        focusElement.focus();
        if (typeof  focusElementstr === "HTMLInputElement")
            focusElement.select();
    }

    
} // end: class
Craig D
  • 351
  • 2
  • 7
-1

The easiest way to ask before action on click is following

<a onclick="return askyesno('Delete this record?');" href="example.php?act=del&del_cs_id=<?php echo $oid; ?>">
<button class="btn btn-md btn-danger">Delete </button>
</a>
Hassan Qasim
  • 463
  • 5
  • 5
-3
document.getElementById("button").addEventListener("click", function(e) {
   var cevap = window.confirm("Satın almak istediğinizden emin misiniz?");
   if (cevap) {
     location.href='Http://www.evdenevenakliyat.net.tr';       
   }
});
Aman Gupta
  • 5,548
  • 10
  • 52
  • 88
alpc
  • 598
  • 3
  • 6