Gaurav
Gaurav

Reputation: 8487

creating confirm dialog in jquery

$("#first").dialog({ width: 304, modal: true,

  beforeclose: function (e, ui) 
  {
        $("#confirm").dialog({ width: 500, modal: true,
            buttons: {
                "Confirm": function () {
                    document.location.href = "/Home/Index";
                },
                "Cancel": function () {
                    $(this).dialog('close');
                    return false;
                }
            }
        });
    }
});

The dialog #first closes without waiting for the #confirm dialog to open. I know about confirm() function of javascript but i want to use dialog in this case . How can i do that?

Upvotes: 3

Views: 4718

Answers (2)

mu is too short
mu is too short

Reputation: 434985

From the fine manual:

beforeClose(event, ui)

Triggered when a dialog is about to close. If canceled, the dialog will not close.

So you want your beforeClose handler to return false to keep the dialog from closing:

beforeClose: function(e, ui) {
    $("#confirm").dialog({ width: 500, modal: true, /* ... */ });
    return false;
}

Your Confirm button changes the location so you don't have to worry about your beforeClose handler preventing the second dialog from closing the first one. If you weren't changing the page location then you'd need a flag of some sort to keep beforeClose from preventing all closes; something like this for example:

beforeclose: function(e, ui) {
     var $dlg = $(this);
     if($dlg.data('can-close')) {
         $dlg.removeData('can-close');
         return true;
     }
     $("#confirm").dialog({
         //...
         buttons: {
             Confirm: function() {
                 $(this).dialog('close');
                 $dlg.data('can-close', true);
                 $dlg.dialog('close');
             },
             Cancel: function() {
                 $(this).dialog('close');
             }
         }
     });
     return false;
 }

Demo: http://jsfiddle.net/ambiguous/jYZpD/

Upvotes: 8

Gaurav
Gaurav

Reputation: 8487

I am going to answer my own question and this is working fine:

$("#first").dialog({ width: 304, modal: true,

  beforeclose: function (e, ui) 
  {
        $("#confirm").dialog({ width: 500, modal: true,
            buttons: {
                "Confirm": function () {
                    document.location.href = "/Home/Index";
                },
                "Cancel": function () {
                    $(this).dialog('close');
                }
            }
        });
      return false;
    }
});

Upvotes: 3

Related Questions