Sweet Alert 确认后继续提交表单

18

我在表单提交时触发了这个sweetalert。

$(".swa-confirm").on("submit", function(e) {
        e.preventDefault();
        swal({
            title: $(this).data("swa-title"),
            text: $(this).data("swa-text"),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#cc3f44",
            confirmButtonText: $(this).data("swa-btn-txt"),
            closeOnConfirm: false,
            html: false
        }, function() {

        }
        );
    });

但在点击确认后,我希望它继续提交表单...

会浮现出一些不好的想法,比如:

var confirmed = false;
$(".swa-confirm").on("submit", function(e) {
    var $this = $(this);
    if (!confirmed) {
        e.preventDefault();
        swal({
            title: $(this).data("swa-title"),
            text: $(this).data("swa-text"),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#cc3f44",
            confirmButtonText: $(this).data("swa-btn-txt"),
            closeOnConfirm: true,
            html: false
        }, function() {
            confirmed = true;
            $this.submit();
        });
    }
});

或者将swa移动到按钮点击事件中,而不是在提交表单时使用on submit事件。

但我不喜欢这个解决方案,它看起来像弗兰肯斯坦一样。肯定有更好的方法。

13个回答

37
$('#btn-submit').on('click',function(e){
    e.preventDefault();
    var form = $(this).parents('form');
    swal({
        title: "Are you sure?",
        text: "You will not be able to recover this imaginary file!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete it!",
        closeOnConfirm: false
    }, function(isConfirm){
        if (isConfirm) form.submit();
    });
});

我认为你漏掉了一个分号; 但除此之外,我喜欢你的答案 ;) - CoalaWeb
2
这不会执行任何表单验证。 - Abhijeet Ahuja
@Abhijeet 请查看 https://dev59.com/MVwY5IYBdhLWcg3w0KvL#69026840 - Jaber Al Nahian
谢谢!这对我有用。 - Sanushi Salgado

9

我知道这可能有点晚,但对未来的某些人可能有所帮助。我已成功地使用它来提交带有sweetalert确认框的表单。

 $('#form_id').submit(function (e, params) {
        var localParams = params || {};

        if (!localParams.send) {
            e.preventDefault();
        }

           //additional input validations can be done hear

    swal({
                title: "Confirm Entry",
                text: "Are you sure all entries are correct",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#6A9944",
                confirmButtonText: "Confirm",
                cancelButtonText: "Cancel",
                closeOnConfirm: true
            }, function (isConfirm) {
                if (isConfirm) {
                    $(e.currentTarget).trigger(e.type, { 'send': true });
                } else {

              //additional run on cancel  functions can be done hear

            }
        });
});

如果您将整个 swal 函数放在 preventDefault 之后的 if 循环内部,那就更好了。 - Máté Gregor

5

这是另一个示例,要求用户通过复选框进行确认。

HTML

<form id="myForm">
    <button type="submit" id="btn-submit">Submit</button>
</form>

JavaScript

$(document).on('click', '#btn-submit', function(e) {
    e.preventDefault();
    swal({
        title: 'Confirm',
        input: 'checkbox',
        inputValue: 0,
        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) {
        $('#myForm').submit();
    });
});

4
我认为这样更加优雅一些:

$(".swa-confirm").submit(function (e) {
    e.preventDefault();
    swal({
        title: $(this).data("swa-title"),
        text: $(this).data("swa-text"),
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#cc3f44",
        confirmButtonText: $(this).data("swa-btn-txt"),
        closeOnConfirm: false,
        html: false
    }, function(){
        $(".swa-confirm").off("submit").submit();
    });
});

3
"最初的回答" 翻译成英文是 "Original Answer"
为了让这个方法百分之百有效,请在表单中添加一个属性,比如 data-flag,并将其赋值为 "0",表示假。通过这种小技巧来实现。
<form class="swa-confirm" data-flag="0">
    //your inputs
</form>

In your jquery.

$(".swa-confirm").on("click", function(e) {
    $flag = $(this).attr('data-flag');

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

        swal({
            title: $(this).data("swa-title"),
            text: $(this).data("swa-text"),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#cc3f44",
            confirmButtonText: $(this).data("swa-btn-txt"),
            closeOnConfirm: true,
            html: false
        }, function( confirmed ) {
            if( confirmed ){
                // if confirmed change the data-flag to 1 (as true), to submit
                $('.swa-confirm').attr('data-flag', '1');
                $('.swa-confirm').submit();
            }
        });
    }

    return true;
});

2
var form = $(this).parents('form');   
    swal({
        title: "Are you sure?",
        icon: "warning",
        buttons:[
            'No, cancel it!',
            'Yes, I am sure!'
            ],
            }).then(function(isConfirm){        
                if(isConfirm){ 
                        form.submit();
                } 
});

2

function testalert(){

swal(

    {
        title              : "Are you sure?",
        text               : "You want to save?",
        type               : "warning",
        allowEscapeKey     : false,
        allowOutsideClick  : false,
        showCancelButton   : true,
        confirmButtonColor : "#DD6B55",
        confirmButtonText  : "Yes",
        showLoaderOnConfirm: true,
        closeOnConfirm     : false
    }, 

    function (isConfirm) {

        if (isConfirm) {
            profileinfo.submit();
            return true;
        }

        return false;

    }

);

}


<button id="prty_form_save" type="button" onclick="return testalert();">保存</button> 按钮类型必须为 button(不要使用 input 类型 = submit) - pradeep

1
你可以使用这个。

$('#deleteamc').on('click',function(e) {
    
    event.preventDefault();
var form = this;
    
        swal({
  title: "Are you sure?",
  text: "All data related to this AMC ID will be parmanently deleted",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Yes, DELETE it!",
  cancelButtonText: "No, cancel please!",
  closeOnConfirm: false,
  closeOnCancel: false
},
function(isConfirm){
  if (isConfirm) {
   form.submit();
   } else {
    swal("Cancelled", "AMC Record is safe :)", "error");
 
  }
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<form method="POST" id="deleteform">
        <input type="hidden" name="amccode" id="amccode" value="<?php echo $row['amccode']; ?>">
        <button class="btn btn-danger" id="deleteamc" name="delete" type="submit">
            <i class="fa fa-minus"></i>
                Delete
        </button>
</form>


1
将类名 .swa-confirm 应用于提交按钮
$(".swa-confirm").on("click", function(e) {
    e.preventDefault();
    swal({
        title: $(this).data("swa-title"),
        text: $(this).data("swa-text"),
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#cc3f44",
        confirmButtonText: $(this).data("swa-btn-txt"),
        closeOnConfirm: true,
        html: false
    }, function( confirmed ) {
        if( confirmed )
            $(this).closest('form').submit();
    });
});

首先阻止按钮事件。之后,启动sweetalert,如果"确认"为真,则提交#my-form元素。

对不起我的英语不好,来自墨西哥的问候,我使用Google翻译 :v。


不对,我的版本更好。因为我没有硬编码表单名称。 - user796443
我做了一个更改,你觉得怎么样? - Rafael Cuevas
好的,谢谢,但是这个概念与我的版本并没有改变很多?我正在寻找一些简单明了的东西。 - user796443
好的,希望你能找到更舒适、更美观的东西。Sweet Alert 看起来不错,但使用起来还是有点丑。 - Rafael Cuevas
你应该使用“提交”而不是“点击”,因为现在大多数浏览器都会在开始时进行验证,这对你的用户来说会更好。 - Marek Szmalc
@MarekSzmalc 请查看 https://dev59.com/MVwY5IYBdhLWcg3w0KvL#69026840 - Jaber Al Nahian

0

如果你有多个提交按钮,这里是使用 Vanilla Javascript 的版本。 不需要 jQuery

<button class="submit" type="submit" 
     data-confirm="Are you sure you want to submit this?" 
     data-icon="warning" 
     data-color="#e55353">
       Submit
</button>

        document.querySelectorAll('.submit').forEach(item => {
            item.addEventListener('click', function(event){
                event.preventDefault();
                let form = this.closest('form');
                Swal.fire({
                    icon: this.getAttribute('data-icon'),
                    text: this.getAttribute('data-confirm'),
                    showCancelButton: true,
                    confirmButtonText: 'Yes',
                    cancelButtonText: 'No',
                    iconColor: this.getAttribute('data-color'),
                    confirmButtonColor: this.getAttribute('data-color'),
                }).then((result) => {
                    if (result.isConfirmed) {
                        form.submit();
                    }
                })
            })
        });


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