I want to replace my project's confirms with SweetAlert2 dialogs but I'm having a problem handling cancel. I want that when clicking on a checkbox it shows a confirmation dialog and that if the user clicks on the cancel button the checkbox does not remain selected.
My code:
$(element).click(function (e) {
swal({
title: 'Seleccionado',
text: "¿Está seguro que desea seleccionarlo?",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si',
cancelButtonText: 'No'
}).then((result) => {
if (result.value) {
guardar(true);
} else {
return false;
}
});
});
For some reason when you click "No" it executes what you put in the else but the checkbox remains selected.
Any idea how to fix it?
It is correct to return
true | false
to cancel the user action.However, when you use javascript asynchronously (
swal({}).then((...)=>{})
), you should be aware that the browser is executing your handler as a regular function,() => {}
not an asynchronous functionasync () => {}
.So even still declaring the handler as an asynchronous function, and using the
await
. The browser would not expect this behavior and you would not be able to return the desired value.To try to explain it better, I leave you a lab with async / await syntax for the
Promise
swal one.This fragment is just a lab
In it you will be able to appreciate how the handler assigned to the event constantly returns a positive value for a logical operation, destroying any reaction of the user to cancel his action.
a possible answer
On the other hand, there are different ways to achieve the proposed operation.
In the following solution we will keep the syntax
swal({}).then(...){}
to achieve asynchronous operation, performing a double check through the custom propertydata-sure
.Our handler will return
false
to avoid changing the state of our checkbox and display the componentswal
to the user.When
swal
the resolved promise returns, we will evaluate the result.With an affirmative result, we will mark
data-sure
atrue
and re-execute the 'click' event handler programmatically.If it
checkbox
contains the custom propertydata-sure
or, failing that, it was already 'marked' by the user. We will allow the actionreturn true
.See in operation
I hope it will be useful =)
welcome to stackoverflow