I'm trying to add a nice confirmation message using Sweetalert2 to the bootstrap version 5 alert component.
how does it work?
when I clicked to "Close Button" (X) it should display a confirmation message with two options (Yes) and (No) if I clicked to (Yes) the alert component should be closed if (No) the alert component should be displayed.
that's it.
the issue that I face is in the close event when I put this code inside it and clicked to (Yes) Option in sweatalert2 confirmation message it shows me an error message in my dev console!
reference: https://getbootstrap.com/docs/5.0/components/alerts/#dismissing
HTML code:
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
JS code:
if ($(".alert").length) {
$(".alert").on("close.bs.alert", function (e) {
e.preventDefault();
var swalWithBootstrapButtons = Swal.mixin({
customClass: {
confirmButton: "btn btn-primary",
cancelButton: "btn btn-danger me-3",
},
buttonsStyling: false,
});
swalWithBootstrapButtons
.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
confirmButtonText: "<i class='fas fa-check-circle me-1'></i> Yes, I am!",
cancelButtonText: "<i class='fas fa-times-circle me-1'></i> No, I'm Not",
showCancelButton: true,
reverseButtons: true,
focusConfirm: false,
})
.then((result) => {
if (result.isConfirmed) {
var alertNode = document.querySelector(".alert");
var alert = bootstrap.Alert.getInstance(alertNode);
alert.close();
}
});
});
}