如何使用Sweet Alert进行确认操作?

45

即使我点击"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");
    }
 });
};

4
添加这个语句:event.preventDefault(); - Pratik
1
@Pratik 仍然不起作用。 - user5065157
14个回答

58

当提交表单时,您需要防止默认的表单行为。之后,如果选择“确定”按钮,则需要通过编程方式提交表单。

这是它可能看起来的样子:

document.querySelector('#from1').addEventListener('submit', function(e) {
  var form = this;

  e.preventDefault(); // <--- prevent form from submitting

  swal({
      title: "Are you sure?",
      text: "You will not be able to recover this imaginary file!",
      icon: "warning",
      buttons: [
        'No, cancel it!',
        'Yes, I am sure!'
      ],
      dangerMode: true,
    }).then(function(isConfirm) {
      if (isConfirm) {
        swal({
          title: 'Shortlisted!',
          text: 'Candidates are successfully shortlisted!',
          icon: 'success'
        }).then(function() {
          form.submit(); // <--- submit form programmatically
        });
      } else {
        swal("Cancelled", "Your imaginary file is safe :)", "error");
      }
    })
});

更新。上面的示例使用了sweetalert v2.x promise API。

演示: http://plnkr.co/edit/YTY7PDs5Uh1XGUo9ic1s?p=preview


现在我点击“确定”按钮后什么也没有发生。它卡在了Sweet Alert上。 - user5065157
未捕获的类型错误:对象不是函数正在显示。 - user5065157
请检查工作演示。然后将其与您的代码进行比较,您可能混淆了某些内容。 - dfsq
检查了你的代码,但在我的代码中无法运行,仍然显示相同的错误。 - user5065157
当我尝试重定向到主页时,使用解决方案时,我遇到了以下错误:this.router.navigate(['']);core.js:6142 ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'router') - Jignesh Panchal
显示剩余4条评论

10
document.querySelector('#from1').onsubmit = function(e){

 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");
         e.preventDefault();
    }
 });
};

1
即使我没有点击任何按钮,表单仍在提交。这是一个警报的闪光,但随后表单被提交了。 - user5065157
1
这是不正确的,e.preventDefault必须在匿名函数之外。 - Ibu
无论函数在做什么,代码都会运行。 - ricks

9

我也遇到了SweetAlert2的这个问题。SA2与1有所不同,将所有内容放在结果对象中。以下代码可实现上面的内容。

Swal.fire({
    title: 'A cool title',
    icon: 'info',
    confirmButtonText: 'Log in'
  }).then((result) => {
    if (result['isConfirmed']){
      // Put your function here
    }
  })

then结果中的所有内容都将运行。Result包含一些参数,可以用来解决问题。这是一个非常简单的技术。不确定它是否在SweetAlert1上有效,但我真的不知道为什么会选择那个版本而不是更新版本。


这就是我在SA2中寻找的,谢谢。 - duffn

8

你需要使用then()函数,就像这样

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
我收到了 TypeError: 无法读取未定义的属性('then')... 我不会使用sweetalert2。 - Jaxx0rr

4

document.querySelector('#from1').onsubmit = function(e){

 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.value){
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");

    } else {
      swal("Cancelled", "Your imaginary file is safe :)", "error");
         e.preventDefault();
    }
 });
};


1
不需要使用 isConfirm.value,你可以使用 if (isConfirm) { ... }。如果确认了,它将返回 true。 - Roy Ryando
这里的命名很令人困惑。输入应该是result而不是isConfirm。这个result对象包含属性,如isConfirmedvalueisDenied(https://sweetalert2.github.io/#three-buttons)。 - Ben Jones
1
我不得不将 if (isConfirm.value) 更改为 if (isConfirm),以便正确评估用户操作返回的布尔值 - 否则这是我这里唯一有效的示例。 - cloudxix

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

2
在使用这段代码时,我遇到了以下错误:“无法读取未定义的属性'then' 在Object._navigation.onsuccesssignout处” - user8718405
你正在使用哪个版本的jQuery?尝试使用最新的jQuery版本。 - Hiran D.A Walawage
1
这段代码总是显示“确认按钮已单击”,你应该添加if条件来检查是否点击了确定。 - Firas Nizam
你可以在then函数内实现任何内容。我只是为了演示使用了alert。 - Hiran D.A Walawage

3
在您的保存按钮内部点击添加此代码:
$("#btnSave").click(function (e) {
  e.preventDefault();
  swal("Are you sure?", {
    buttons: {
      yes: {
        text: "Yes",
        value: "yes"
      },
      no: {
        text: "No",
        value: "no"
      }
    }
  }).then((value) => {
    if (value === "yes") {
      // Add Your Custom Code for CRUD
    }
    return false;
  });
});

3

百分之百有效

使用属性来进行小技巧。在你的表格中添加一个像 data-flag 这样的属性,把“0”赋值为false。

<form id="from1" data-flag="0">
    //your inputs
</form>

在你的JavaScript代码中:

document.querySelector('#from1').onsubmit = function(e){

    $flag = $(this).attr('data-flag');

    if($flag==0){
        e.preventDefault(); //to prevent submitting

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

                //update the data-flag to 1 (as true), to submit
                $('#from1').attr('data-flag', '1');
                $('#from1').submit();
            } else {
                swal("Cancelled", "Your imaginary file is safe :)", "error"); 
            }
         });
    }

    return true;
});

1

甜蜜警告 V1

swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes',
    cancelButtonText: "No",
    closeOnConfirm: false,
    closeOnCancel: true
},
function(resp) {
    console.log(resp)
    if (resp) {
        console.log("sssssssssssssiiiii")
    } else {
        console.log('noooooooooooooooooooo')
    }
});

甜蜜警告框 V2

swal({
    title: "Are you sure?",
    text: "Once deleted, you will not be able to recover this imaginary file!",
    icon: "warning",
    buttons: true,
    dangerMode: true,
})
.then((willDelete) => {
    if (willDelete) {
        swal("Poof! Your imaginary file has been deleted!", {
            icon: "success",
        });
    } else {
        swal("Your imaginary file is safe!");
    }
});

1
检查确认或取消按钮是否被按下:
     swal2.fire({
            title: 'Your Title',
            input: 'textarea',
            inputAttributes: {
                autocapitalize: 'off'
            },
            showCancelButton: true,
            confirmButtonText: 'ok',
            cancelButtonText: 'cancel',
            allowOutsideClick: false
        }).then((result) => {
            if (result.dismiss !== 'cancel') {

                alert('confirm pressed');
            }
           else
            {
                alert('cancel pressed');

            }
        })

如果您使用Swal,请将swal2更改为Swal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接