When working in ASP.Net, I often like to have "Are you sure?" popups when clicking things like a delete button. This is easily done like so:
<asp:Button runat="server" id="btnDelete" Text="Delete" onClientClick="return confirm('Are you sure?');" onClick="btnDelete_Click" />
I really like the styling and general feel of SweetAlert2's confirm dialog, however they're seemingly a bit more troublesome when I'm attempting to integrate them in a similar fashion. Can someone explain to me how I might be able to return the SweetAlert2 dialog result to either continue or stop based on the button clicked?
Here's what I've got so far:
<asp:Button runat="server" id="btnDelete" Text="Delete" onClientClick="return sweetAlertConfirm();" onClick="btnDelete_Click" />
function sweetAlertConfirm() {
event.preventDefault();
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
// }).then(function() {
// CONFIRM WAS CHOSEN
// }, {function() {
// CANCEL WAS CHOSEN
});
}
The dialog comes up and the delete is not processed, of course, as I'm currently doing an event.preventDefault()
and nothing is being returned. I'm also noticing that I can use promises, adding a .then()
after my swal({...})
, however I'm not sure how that would be used in this instance.
If need be I can get tricky with a hidden button that actually triggers the code-behind method, and click that hidden button based on the user selection, but I'm hoping to avoid this.
Since the SweetAlert2 dialog is processed asynchronously, you have to trigger another button click programmatically when the promise is resolved. Instead of creating a hidden button, you can reuse btnDelete
by setting a flag to indicate that the action was already confirmed. That flag will be detected when the second click is processed, and the button click will be allowed to proceed and to trigger the server event.
<asp:Button ... OnClientClick="return sweetAlertConfirm(this);" OnClick="btnDelete_Click" />
function sweetAlertConfirm(btnDelete) {
if (btnDelete.dataset.confirmed) {
// The action was already confirmed by the user, proceed with server event
btnDelete.dataset.confirmed = false;
return true;
} else {
// Ask the user to confirm/cancel the action
event.preventDefault();
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
})
.then(function () {
// Set data-confirmed attribute to indicate that the action was confirmed
btnDelete.dataset.confirmed = true;
// Trigger button click programmatically
btnDelete.click();
}).catch(function (reason) {
// The action was canceled by the user
});
}
}
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