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; } } });
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 }
If anyone needs a graphic demonstration of asynchronous behavior, here's one that might be helpful. Wrap Ronedog's dialog in a function. I've used "showConfirm" below. Capture the return value in a variable. Call it in some button click event, and try to alert what button was pressed:
$('.btn').on('click', function(event) { var cVal = showConfirm('Really?'); alert('User pressed ' + cVal); });
You will find that you always get the alert before you have a chance to press the button. Since javascript is asynchronous, the alert function doesn't have to wait for the result of the showConfirm function.
If you then set up the function Neal's way everything will work (thanks Neal).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With