Ronedog Ronedog - 27 days ago 7
jQuery Question

jquery ui dialog box need to return value, when user presses button, but not working

I'v got a jquery ui dialog box I want to use to prompt the user to confirm a deletion. When the user presses "yes" or "no" I need to return "True" or "False" to continue some javascript execution. The problem with the code below is when the dialog box shows up it immediately is executing a "return true;" but the user hasn't pressed the "Yes" button yet?

What am I doing wrong?

HTML:

<div id="modal_confirm_yes_no" title="Confirm"></div>


Javascript call:

$("#modal_confirm_yes_no").html("Are you sure you want to delete this?");
var answer = $("#modal_confirm_yes_no").dialog("open");

if (answer)
{
//delete
}
else
{
//don't delete
}


Jquery dialog:

$("#modal_confirm_yes_no").dialog({
bgiframe: true,
autoOpen: false,
minHeight: 200,
width: 350,
modal: true,
closeOnEscape: false,
draggable: false,
resizable: false,
buttons: {
'Yes': function(){
$(this).dialog('close');
return true;
},
'No': function(){
$(this).dialog('close');
return false;
}
}
});

Answer

javascript is asynchronous.

so you have to use callbacks:

   $("#modal_confirm_yes_no").dialog({
            bgiframe: true,
            autoOpen: false,
            minHeight: 200,
            width: 350,
            modal: true,
            closeOnEscape: false,
            draggable: false,
            resizable: false,
            buttons: {
                    'Yes': function(){
                        $(this).dialog('close');
                        callback(true);
                    },
                    'No': function(){
                        $(this).dialog('close');
                        callback(false);
                    }
                }
        });
    function callback(value){
         //do something
    }