Diskdrive Diskdrive - 26 days ago 5
Javascript Question

How do I get a JQuery statement to wait until it's completed before continuing?>

Firstly, I'm new at Javascript / Jquery so it might be a stupid question...

I'm using the dialog box that is in the JQuery UI collection. I have a button that when clicked, it either shows a confirm box or an alert box. My code is like below...

function checkfn() {

if (document.getElementById('<%=HomeInstSelected.ClientID%>').value == 'False') {

var dialogResult = false;

$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
Continue: function () {
dialogResult = true;
$(this).dialog("close");

},
Cancel: function () {
$(this).dialog("close").slideUp();
}
}
});

// alert just debug code!
alert(dialogResult);
return dialogResult;

}
else {
$("#dialog-HomeInstitutionPrompt").dialog({
height: 140,
modal: true
});

}
}


My problem is in the confirm part, it seems the confirm box is not waiting for me to hit Continue or Cancel - it's just going straight to the alert part and returning dialogResult = false.

Is it possible to halt execution of until after I've run the $('#dialog-confirm') command?

Alternatively, is it possible to return true for the checkfn() function, in the Continue function? That way, I will not need a dialogResult var at all?

Answer

I haven't used the .dialog in jQuery UI before, but, in general with jQuery, functions are run asynchronously. What this means is that you need to put the code that you want run in the Continue function.

One possibility is to send a success/cancel function to checkfn that you would call from the Continue and Cancel functions.

function checkfn(success, cancel) {

if (document.getElementById('<%=HomeInstSelected.ClientID%>').value == 'False') {

    var dialogResult = false;

    $("#dialog-confirm").dialog({
        resizable: false,
        height: 140,
        modal: true,
        buttons: {
            Continue: function () {
                if(success) success();
                $(this).dialog("close");

            },
            Cancel: function () {
                if(cancel) cancel();
                $(this).dialog("close").slideUp();
            }
        }
    });
}

You can call the function like this:

checkfn(function () {
    alert('success!');
}, function () {
    alert('failure!');
});