【问题标题】:SweetAlert2 Cancel button still submitting formSweetAlert2 取消按钮仍在提交表单
【发布时间】:2018-02-16 07:55:41
【问题描述】:

我有一个简单的表单,我正在尝试使用 SweetAlert2 让用户在提交和处理表单之前确认他们的提交。

我正在使用下面的代码来中断提交流程,但是无论用户是否按下模式取消点击,表单都会提交。有谁知道我做错了什么?

<script>

$(document).on('click', '#note_submit', function(e) {
    e.preventDefault();
    swal({
        title: "Are you sure?",
         text: "Once deleted, you will not be able to recover this imaginary file!",
        buttons: true,
        dangerMode: true,
        icon: "warning",
        input: 'checkbox',
        inputValue: 0,
        showCancelButton: true,
        inputPlaceholder: ' I agree with the Terms',
        confirmButtonText: 'Continue',
        inputValidator: function (result) {
            return new Promise(function (resolve, reject) {
                if (result) {
                    resolve();
                } else {
                    reject('You need to agree with the Terms');
                }
            })
        }
    }).then(function (result) {
        $('#notes_form').submit();
    });
});


</script>

【问题讨论】:

标签: javascript sweetalert sweetalert2


【解决方案1】:

因为你提到了inputValidator参数,我相信你使用的是SweetAlert2,而不是SweetAlert

我的另一个猜测是,您最近将 SweetAlert2 更新到了最新版本,并且没有检查发行说明中的​​重大更改:https://github.com/sweetalert2/sweetalert2/releases/tag/v7.0.0

从 v7.0.0 开始,SweetAlert2 将始终履行承诺,为了检查对话是否已提交或取消,您需要检查result.value

Swal.fire({
  ...
}).then((result) => {
  if (result.isConfirmed) {
    // A dialog has been submitted

  } else if (result.isDismissed) {
    // A dialog has been cancelled
    // For more information about handling dismissals please visit
    // https://sweetalert2.github.io/#handling-buttons
  }
})

【讨论】:

    【解决方案2】:

    SweetAlert 使用承诺来跟踪用户如何与警报交互。

    If the user clicks the confirm button, the promise resolves to true. 
    If the alert is dismissed (by clicking outside of it), the promise resolves to null.
    

    提交前检查result

    ....    
    .then(function (result) {
       if(result){
           $('#notes_form').submit();
       }
      });
    

    【讨论】:

      【解决方案3】:

      不要使用then

      替换那个

      }).then(function (result) {
              $('#notes_form').submit();
      });
      

      这将只在OK 动作中执行你所拥有的内容

      }, function() {
              $('#notes_form').submit();
      });
      

      Cancel 按钮应该具有默认行为并关闭 swal 对话框,而无需您做任何事情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多