如何使用SweetAlert2捕获表单提交方法

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

我的javascript知识也很差所以请帮助。 我正在尝试保护用户页面并添加确认对话框以进行删除。 但我不知道如何捕获提交方法。 我使用 sweetalert2 的确认, 但不幸的是,表单方法运行时无需单击任何按钮。

所以我的问题是如何修改代码?

<form action="{{ route('users.destroy', ['user' => \Illuminate\Support\Facades\Auth::id()]) }}" method="post">
    @csrf
    @method('DELETE')
    <button id="comfirm-delete" class="btn btn-danger">User Delete</button>
</form>


<script>
    $(function () {
      'use strict';

      var comfirmDelete = $('#comfirm-delete');

      if (comfirmDelete.length) {
        comfirmDelete.on('click', function() {
          Swal.fire({
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            showCancelButton: true,
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'No, cancel!',
            customClass: {
              confirmButton: 'btn btn-primary',
              cancelButton: 'btn btn-outline-danger ml-1'
            },
            buttonsStyling: false
          }).then(function(result) {
            if (result.value) {
              Swal.fire({
                icon: 'success',
                title: 'Deleted!',
                text: '',
                customClass: {
                  confirmButton: 'btn btn-success'
                }
              });
            }
          });
        });
      }

    });
 </script>
javascript forms try-catch laravel-blade sweetalert2
2个回答
0
投票

这是方法

如果您有多个表单,则需要一个类并缓存表单,而不是使用

$('#myForm')

$(function() {
  const $myForm = $('#myForm')
    .on('submit', function(e) {
      e.preventDefault();
      Swal.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        showCancelButton: true,
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'No, cancel!',
        customClass: {
          confirmButton: 'btn btn-primary',
          cancelButton: 'btn btn-outline-danger ml-1'
        },
        buttonsStyling: false
      }).then(function(result) {
        if (result.value) {
          Swal.fire({
            icon: 'success',
            title: 'Deleted!',
            text: '',
            customClass: {
              confirmButton: 'btn btn-success'
            }
          });
          setTimeout(function() {
            $myForm[0].submit()
          }, 2000); // submit the DOM form
        }
      });
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.all.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.min.css" rel="stylesheet" />
<form id="myForm">
  <button class="confirm-delete btn btn-danger">User Delete</button>
</form>


0
投票

如果我能看到错误之一是, 我看的是按钮而不是表格?

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