I want to use e.preventDefault();
to prevent the deselection of an option by the user only if user responds No to a confirmation dialog. The confirmation dialog opens only if the result of an ajax call is true.
What I have tried so far is to create a function that makes the ajax call and returns the promise.
> function ajaxCall(action, url, data){
var def = $.ajax({... def.done(function(result){... def.fail(... return def.promise(); }
Using the same pattern, I created a function to wait for the user input.
function displayConfirmationDeg() {
var dialogComp=$(’
var defer = $.Deferred();
dialogComp.dialog(
{
autoOpen: false,
resizable: false,
modal: true,
title: "title",
close: function() {
},
buttons: [{ html: "<i class='ace-icon fa fa-check bigger-110'></i>Yes", "class" : "btn btn-info btn-xs",
click: function() {
defer.resolve("true");
$(this).dialog("close");
}
},
{ html: "<i class='ace-icon fa fa-times bigger-110'></i>No", "class" : "btn btn-xs btn-reset",
click: function() {
defer.resolve("false");
$( this ).dialog( "close" );
}
}]
}
).html("<div class='alert alert-info bigger-110 no-margin-bottom align-center'> Message here </div>");
if (dialogComp.dialog("isOpen")===true){return false;}
dialogComp.dialog('open');
return defer.promise();
}
And finally chain those two in the following.
$(’.’+currentSelect.attr(‘id’)).on(‘select2:unselecting’, function (e) {
$
.when(ajaxCall(‘POST’, ‘/url/’,…)
.then(function(result){
if(result){
$
.when(displayConfirmationDeg())
.then(function(answer){
if(answer==‘false’){
e.preventDefault();
}
})
}
})
})
However when the user deselects an option, the option is removed before the confirmation dialog opens.
Also to make sure that this logic is executed before the deselection, I am using the “.on(‘select2:unselecting’”, yet it doesn’t work as expected.