sweetalert 和表单提交

问题描述 投票:0回答:1

我有一个表单,我想在提交时触发警报(使用 sweetalert):

<form id="verbale" class="verbale" action="editor_conferma.php" method="post">
...
<input id="go" type="submit" name="go" value="go" class="swa-confirm">
</form>

<script>
$(document).on("submit", ".swa-confirm", function (e) {
                e.preventDefault();
                var $myForm = $('.verbale');
                if (!$myForm[0].checkValidity()) {
                    $myForm[0].reportValidity()
                } else {
                    swal({
                        title: "Are you sure?",
                        text: "Did you check?",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonText: "Yes, Submit!",
                    }).then(function (result) {
                        $myForm.submit();
                    });
                }
            });
</script>

出现 sweetalert 对话框,但当我确认时,表单未传递并且提交似乎不起作用。

有什么提示吗?

javascript forms submit sweetalert
1个回答
0
投票

您需要将提交分配给表单,并且不要使用 jQuery 提交,因为它会再次触发 sweetalert

我还使用最新版本的 swal,它有

buttons

$("#verbale").on("submit", function(e) { // or if inserted $(document).on("submit","#verbale",function() {
  e.preventDefault();
  const myForm = this;
  if (!myForm.checkValidity()) {
    myForm.reportValidity()
  } else {
    swal({
      title: "Are you sure?",
      text: "Did you check?",
      icon: "warning",
      buttons: {
        cancel: true,
        confirm: true,
      }
    }).then(function(result) {
      myForm.submit()
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>

<form id="verbale" class="verbale" action="editor_conferma.php" method="post">
  <input type="text" name="firstname" required />
  <input id="go" type="submit" name="go" value="go" class="swa-confirm">
</form>

© www.soinside.com 2019 - 2024. All rights reserved.