ITWorker ITWorker - 4 months ago 17
jQuery Question

jQueryUI dialog replacement for confirm?

I am trying to override the default confirmation box with the jQueryUI dialog box, and here is my attempt:

window.confirm = function (message_confirm) {
$(document.createElement('div'))
.attr({ title: 'Please confirm', 'class': 'confirm', 'id': 'dialogconfirm' })
.html(message_confirm)
.dialog({
buttons: { YES: function () { return true; }, NO: function () { $(this).dialog('close'); } },
close: function () { $(this).remove(); },
draggable: true,
modal: true,
resizable: false,
width: 'auto',
hide: { effect: "fade", duration: 300 },

});

};


This works in that once this script is run, calling a regular
confirm
shows the jQueryUI dialog, however, the
YES
selection does not work. I have an ajax call like below:

if (confirm("Are you sure you want to delete this user?"))
{
alert("test");
//ajax call
}
return false;


And the test alert did not appear. The NO slection of the dialog works fine. How can I get the YES to work?

Thank you.

Answer

Because the dialog is asynchronous you can use a deferred approach:

window.confirm = function (message_confirm) {
  var defer = $.Deferred();
  $('<div/>', {title: 'Please confirm', 'class': 'confirm', 'id': 'dialogconfirm', text: message_confirm})
  .dialog({
    buttons: {
      YES: function () {
        defer.resolve("yes");
        $(this).dialog('close');
      }, NO: function () {
        defer.resolve("no");
        $(this).dialog('close');
      }
    },
    close: function () {
      $(this).remove();
    },
    draggable: true,
    modal: true,
    resizable: false,
    width: 'auto',
    hide: {effect: "fade", duration: 300}
  });
  return defer.promise();
};

$(function () {
  confirm("Are you sure you want to delete this user?").then(function(yesno) {
    console.log(yesno);
  });
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>