Hi, i’m trying to understand how sweet alert works, I’ve got a table where each row is a value fetched from my database, and this is the javascript code I’m using to delete each row using a checkbox
$(document).ready(function() {
$('#delete').click(function() {
if (confirm("Are you sure to delete?")) {
var id = [];
$(':checkbox:checked').each(function(i) {
id[i] = $(this).val();
});
if (id.length === 0) {
alert("Please Select Checkbox");
} else {
$.ajax({
url: "controllers/ctrl_client_delete_inbox.php",
method: "POST",
data: {
id: id
},
success: function() {
for (var i = 0; i < id.length; i++) {
$('tr#' + id[i] + '').css('background-color', '#ccc');
$('tr#' + id[i] + '').fadeOut('slow');
}
}
});
}
}
});
});
It is working fine but does show an alert with traditional layout. Can someone help me please?
Many thanks
I’m guessing that it’s this library that you’re using? In which case, you’ll need to change out your call to confirm() with something like this (from the docs):
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
},
function(){
swal("Deleted!", "Your imaginary file has been deleted.", "success");
});
You’re putting the call to swal() inside the call to confirm(), which isn’t going to work.
Sweet Alert doesn’t work in the same way that the built-in confirm function does. Calling confirm('Are you sure?') will return a value of true or false, depending on the user’s choice. With Sweet Alert, you have to give it a function that will be executed if the user confirms.
Here’s an example of how it might look:
$('#delete').click(function() {
var id = [];
$(':checkbox:checked').each(function(i) {
id[i] = $(this).val();
});
if (id.length === 0) {
alert("Please Select Checkbox");
return;
}
swal({
title: "Are you sure you want to delete?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
closeOnConfirm: false
},
function(){
$.ajax({
url: "controllers/ctrl_client_delete_inbox.php",
method: "POST",
data: {
id: id
},
success: function() {
swal("Deleted!", "The selected items have been deleted.", "success");
for (var i = 0; i < id.length; i++) {
$('tr#' + id[i] + '').css('background-color', '#ccc');
$('tr#' + id[i] + '').fadeOut('slow');
}
}
});
});
});
See that when we call swal() we pass in two arguments: an options object to configure how we want the popup to behave, and a function, which will be called if the user chooses to continue. This function contains the actual code to delete the items from the server.