This is a simplified version of what I am trying to do. When a user clicks a button 'ClickMe', I want to call a validation routine that if the color passed in is not blue, ask the user with a jquery.confirm popup if it is OK that the color is not blue and return and return true or false. The problem is that the code after the validation runs right away after the call to the validation routine, it is not waiting for the dialog message to get clicked on.
$("#ClickMe").click(function () {
var color = 'red';
keep_going = validateColor(color);
console.log('value of keep_going: ' + keep_going);
});
async function validateColor(color) {
if (color == 'blue') {
return true;
} else {
$.confirm({
title: 'Notice!',
content: 'Is it OK that the color is not blue?',
type: 'blue',
buttons: {
Continue: {
action: function () {
return true;
}
},
cancel: function () {
return false;
},
}
});
}
}
Wrap the $.confirm
call in a Promise constructor callback function, and instead of returning false/true in the action callbacks, call resolve
with that boolean value as argument. If now the async
function returns that promise, you can await its value in the click handler. For that to work the click handler (callback) must be declared as an async function as well:
$("#ClickMe").click(async function () {
const color = $("[name=color]:checked").val();
const keep_going = await validateColor(color);
console.log('value of keep_going: ' + keep_going);
});
async function validateColor(color) {
if (color == 'blue') {
return true;
}
return new Promise(resolve =>
$.confirm({
title: 'Notice!',
content: 'Is it OK that the color is not blue?',
type: 'blue',
buttons: {
Continue: {
action: function () {
resolve(true);
}
},
cancel: function () {
resolve(false);
},
}
})
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.css"/>
<input type="radio" name="color" value="red" checked>Red<input type="radio" name="color" value="blue">Blue<br>
<button id="ClickMe">Click Me</button>