18

Possible Duplicate:
Yes or No confirm box using jQuery

I see a lot of examples here about replacements for jQuerys standard confirm dialog but don't understand any of them.

If I want to pop-up a confirm dialog using jQuery or jQueryUI. How can i do it and retrieve what button the user clicked ?

Surely there must be a simple way to set up a confirm dialog like an alert("Something!"); command.

Add two buttons to it and set a call back function on yes or no ?

Community
  • 1
  • 1
MayoMan
  • 4,757
  • 10
  • 53
  • 85

3 Answers3

51

Try this one

$('<div></div>').appendTo('body')
  .html('<div><h6>Yes or No?</h6></div>')
  .dialog({
      modal: true, title: 'message', zIndex: 10000, autoOpen: true,
      width: 'auto', resizable: false,
      buttons: {
          Yes: function () {
              doFunctionForYes();
              $(this).dialog("close");
          },
          No: function () {
              doFunctionForNo();
              $(this).dialog("close");
          }
      },
      close: function (event, ui) {
          $(this).remove();
      }
});

Fiddle

MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
13

You can use jQuery UI and do something like this

Html:

<button id="callConfirm">Confirm!</button>

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>​

Javascript:

$("#dialog").dialog({
   autoOpen: false,
   modal: true,
   buttons : {
        "Confirm" : function() {
            alert("You have confirmed!");            
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

$("#callConfirm").on("click", function(e) {
    e.preventDefault();
    $("#dialog").dialog("open");
});

LeftyX
  • 35,328
  • 21
  • 132
  • 193
  • Hi, When I try this the string "Are you sure about this" just appears in my browser. I have put the javascript you added into my ready method for the page but nothing happens when I click the button. – MayoMan Sep 27 '12 at 09:27
  • @user965895: did you try the jsFiddle? It must work. Could you, please, include your script in your question so we can check? – LeftyX Sep 27 '12 at 10:07
  • @user965895: Don't forget you have to include jQuery UI scripts and CSS. – LeftyX Sep 27 '12 at 11:56
  • Can't make the code work. It also just appears on my browser as plain text. Clicking the button does nothing. http://stackoverflow.com/questions/35767749/jquery-confirmation-not-working – ladiesman1792 Mar 03 '16 at 09:34
  • @ladiesman1792: I've tried it with a few browser (Chrome, FF, Edge) and it does work. – LeftyX Mar 03 '16 at 15:21
5

Have you tried using the official JQueryUI implementation (not jQuery only) : ?

Adriano
  • 19,463
  • 19
  • 103
  • 140
immutabl
  • 6,857
  • 13
  • 45
  • 76