Reputation: 18594
I have a confirmation dialog made with jQuery UI.
I'm trying to take appropriate action after the users reaction (whether yes
or no
):
$("button").click(function() {
if (showDialog('Do you want to continue?')) {
console.log("yes");
} else {
console.log("no");
}
});
function showDialog(message) {
var dfd = new $.Deferred();
$("#dialog").dialog({
modal: true,
buttons: {
"Yes": function() {
dfd.resolve();
$(this).dialog("close");
},
"No": function() {
$(this).dialog("close");
}
}
});
$("#dialog").html(message);
}
In my case, I always get a no
.
Also, the no
appears even before a button is clicked. So I assume, this is asynchronous. Is there a way to prevent that, too?
Upvotes: 0
Views: 115
Reputation: 2733
You're on the right path with the deferred, but you weren't actually listening for it to resolve or reject:
$("button").click(function() {
showDialog('Do you want to continue?').then(function() {
console.log("yes");
}, function() {
console.log("no");
})
});
function showDialog(message) {
var dfd = new $.Deferred();
$("#dialog").dialog({
modal: true,
buttons: {
"Yes": function() {
dfd.resolve();
$(this).dialog("close");
},
"No": function() {
dfd.reject();
$(this).dialog("close");
}
}
});
$("#dialog").html(message);
return dfd;
}
Here is your fiddle updated to work https://jsfiddle.net/v86bc028/1/
Edit - second fiddle showing resolve used for both buttons https://jsfiddle.net/35edpgxp/1/
Upvotes: 3
Reputation: 467
You don't need to use $.Deferred
. Also, the logic that would happen when the user press the Yes or No button should be in the functions provided in the "buttons" config option. Like this:
$("button").click(function() {
showDialog('Do you want to continue?');
});
function showDialog(message) {
$("#dialog").dialog({
modal: true,
buttons: {
"Yes": function() {
console.log('yes');
$(this).dialog("close");
},
"No": function() {
console.log('no');
$(this).dialog("close");
}
}
});
$("#dialog").html(message);
}
Upvotes: 0