最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to run a SweetAlert instead of default javascript confirm method - Stack Overflow

programmeradmin0浏览0评论

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

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.

Share Improve this question asked Jul 15, 2015 at 12:51 Knut PedersenKnut Pedersen 2051 gold badge3 silver badges10 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 11

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

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

Add event.preventDefault(); preventDefault();

      $('.confirmation').on('click', function (event) {
         event.preventDefault();
       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"); 
    });

   });

Try this code which is mentioned as in docs:

$('.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!",   
         closeOnConfirm: false 
    }, function(isConfirm){   
           return isConfirm; //Will be either true or false
    });
});

I wrote this function:

function sweetConfirm(title, text) {
        event.preventDefault();
        var target = $(event.target);
        var href = null;
        var form = null;

        if (target.is("a")) href = target.attr("href");
        else if (target.is("button:submit")) form = target.closest("form");
        else if (target.is("button")) href = target.attr("href") || target.attr("value");

        swal({
            title: title,
            text: text,
            type: "warning",
            allowOutsideClick: true,
            showCancelButton: true
        }, function () {
            if (href) window.location.href = href;
            else if (form) form.submit();
        });
    }

sweetConfirm function will accept a submit button, link button or a normal button and will ask before do the action.

You can use it in the following scenarios:

<a type="button" class="btn btn-default" href="/" onclick="return sweetConfirm('Are you sure?')">
    Link Button 1
</a>

<button type="button" class="btn btn-default" href="/" onclick="return sweetConfirm('Are you sure?')">
    Link Button 2
</button>

<form action="/" method="DELETE">
    <input type="hidden" name="id" value="..">
    <button type="submit" class="btn btn-danger" onclick="return sweetConfirm('Are you sure?')">
        Delete
    </button>
</form>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script
    src="https://code.jquery.com/jquery-3.3.1.js"
    integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
    crossorigin="anonymous"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.all.min.js"></script>
</head>
<body>

    <a id="confirmation" href="test">Test</a>

    <script type="text/javascript">
        $('#confirmation').click(function(e) {
e.preventDefault(); // Prevent the href from redirecting directly
var linkURL = $(this).attr("href");
console.log(linkURL)
warnBeforeRedirect(linkURL);
});

        function warnBeforeRedirect(linkURL) {
            Swal({
                title: 'sAre you sure?',
                text: "You won't be able to revert this!",
                type: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.value) {
                    window.location.href = linkURL;
                }
            })

        }



    </script>

</body>
</html>
发布评论

评论列表(0)

  1. 暂无评论