Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a SweetAlert instead of default javascript confirm method

Currently this is the code I use to run a normal confirm window based on the class "confirmation". This is all done with an href link and not on a button onClick event. As the result of the click is to run another code snipped placed in a different file (with the intention to delete a row in db).

$('.confirmation').on('click', function () {
        return confirm('Er du sikker på at du vil slette?');
    });

What I want is to replace the confirm method with this SweetAlert function

    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"); 
});

Anyone know how to do this, what happens when I try to place the sweetalert inside the onClick function is that the alert appears but it automatically delete the row without me having to confirm anything and the alert fades out.

like image 208
Knut Pedersen Avatar asked Jul 15 '15 12:07

Knut Pedersen


2 Answers

I found the solution!

$('.confirmation').click(function(e) {
e.preventDefault(); // Prevent the href from redirecting directly
var linkURL = $(this).attr("href");
warnBeforeRedirect(linkURL);
});

 function warnBeforeRedirect(linkURL) {
    swal({
      title: "Leave this site?", 
      text: "If you click 'OK', you will be redirected to " + linkURL, 
      type: "warning",
      showCancelButton: true
    }, function() {
      // Redirect the user
      window.location.href = linkURL;
    });
  }
like image 190
Knut Pedersen Avatar answered Sep 19 '22 22:09

Knut Pedersen


I made this codepen in case anyone wants to debug. It appears this is working (check the browser console log for when 'done' is printed) http://codepen.io/connorjsmith/pen/YXvJoE

$('.confirmation').on('click', function(){
  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!",
    cancelButtonText: "No, cancel plx!",
    closeOnConfirm: false,
    closeOnCancel: false
  },
  function(isConfirm){
    if (isConfirm) {
      console.log('done');
      swal("Deleted!", "Your imaginary file has been deleted.", "success");
    } else {
        swal("Cancelled", "Your imaginary file is safe :)", "error");
    }
  });
})
like image 42
Connor S Avatar answered Sep 19 '22 22:09

Connor S