jquery ui dialog box as confirm

javascript, jquery, jquery-ui-dialog

Solution

What you need to do is use jQuery.deferred/promise.

http://api.jquery.com/deferred.promise/

In this example, asyncEvent

1)creates a jquery deferred object

2)has logic for resolve/reject, your ok/cancel

3)returns a deferred.promise() object, which can then be used with a $.when to determine if a deferred object is resolved or rejected (ok/cancel).

What you would do is

1)create a jquery deferred object

2)launch your dialog, with ok/cancel setting the deferred.resolve/reject

3)return a deferred.promise() object,

4)Use the deferred promise object with $.when http://api.jquery.com/jQuery.when/

function customConfirm(customMessage) {
    var dfd = new jQuery.Deferred();
    $("#popUp").html(customMessage);
    $("#popUp").dialog({
        resizable: false,
        height: 240,
        modal: true,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
                alert(true);
                dfd.resolve();
            },
            Cancel: function () {
                $(this).dialog("close");
                alert(false);
                dfd.reject();
            }
        }
    });
   return dfd.promise();
}

$.when( customConfirm('hey') ).then(
  function() {
  alert( "things are going well" );
},
function( ) {
  alert( "you fail this time" );
});

You could also just use resolve and determine if the confirm was true or false in the $.when,

function customConfirm(customMessage) {
    var dfd = new jQuery.Deferred();
    $("#popUp").html(customMessage);
    $("#popUp").dialog({
        resizable: false,
        height: 240,
        modal: true,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
                alert(true);
                dfd.resolve(true);
            },
            Cancel: function () {
                $(this).dialog("close");
                alert(false);
                dfd.resolve(false);
            }
        }
    });
   return dfd.promise();
}

$.when( customConfirm('hey') ).then(
  function(confirm) {

   if(confirm){alert( "things are going well" );}
   else{alert( "you fail this time" );}
});

Hope that helps.

Problem

I am, trying to replicate the 'confirm' box of javascript using jquery dialog. This is my code, ``` function customConfirm(customMessage) { $("#popUp").html(customMessage); $("#popUp").dialog({ resizable: false, height: 240, modal: true, buttons: { "OK": function () { $(this).dialog("close"); alert(true); return true; }, Cancel: function () { $(this).dialog("close"); alert(false); return false; } } }); } ``` But when I tried to alert this method, it shows 'undefined'. It is not waiting for the popup to display. How can i make this customConfirm function to wait for the users input(ok/cancel)?. My need is that, customConfirm() method will return either true of false according to user input.

Original source