How to use confirm using sweet alert?

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

In this code form is submitted even i am clicking on no

document.querySelector('#from1').onsubmit = 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, I am sure!',     cancelButtonText: "No, cancel it!",     closeOnConfirm: false,     closeOnCancel: false  },  function(isConfirm){     if (isConfirm){      swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");      } else {       swal("Cancelled", "Your imaginary file is safe :)", "error");     }  }); };

回答1:

You will need to prevent default form behaviour on submit. After that you will need to submit form manually in case of Ok button is selected.

document.querySelector('#from1').addEventListener('submit', function(e) {     var form = this;     e.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, I am sure!',         cancelButtonText: "No, cancel it!",         closeOnConfirm: false,         closeOnCancel: false     },     function(isConfirm) {         if (isConfirm) {             swal({                 title: 'Shortlisted!',                 text: 'Candidates are successfully shortlisted!',                 type: 'success'             }, function() {                 form.submit();             });          } else {             swal("Cancelled", "Your imaginary file is safe :)", "error");         }     }); });

Demo: http://plnkr.co/edit/oJRK5KWRznuIjIuWN8KI?p=preview



回答2:

You need To use then() function, like this

swal({     title: "Are you sure?",     text: "You will not be able to recover this imaginary file!",     type: "warning",     showCancelButton: true,     confirmButtonColor: '#DD6B55',     confirmButtonText: 'Yes, I am sure!',     cancelButtonText: "No, cancel it!"  }).then(        function () { /*Your Code Here*/ },        function () { return false; });


回答3:

swal({     title: 'Are you sure?',     text: "You won't be able to revert this!",     type: 'warning',     showCancelButton: true,     confirmButtonColor: '#3085d6',     cancelButtonColor: '#d33',     confirmButtonText: 'Confirm!' }).then(function(){     alert("The confirm button was clicked"); }).catch(function(reason){     alert("The alert was dismissed by the user: "+reason); });


回答4:

document.querySelector('#from1').onsubmit = function(e){   swal({     title
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!