23

我有一个表单,想拦截表单提交以使用bootbox显示确认对话框。

  1. 用户输入一些数据
  2. 用户点击提交
  3. 显示确认对话框

如果用户点击OK,那么表单应该提交,如果没有,它应该留在页面上。

我试过这个:

$('#myForm').submit(function() {
    return bootbox.confirm("Are you sure?");
});

但是,bootbox.confirm()立即返回,确认对话框再次隐藏。

然后我注意到有一个回调参数bootbox.confirm()。但是,如果我$('#myForm').submit()要从回调中调用,这显然只会再次显示确认对话框。

那么确认表单提交的正确方法是什么?

4

5 回答 5

44

我只是通过阻止默认表单行为来实现这一点,这是下面的解决方案。我在表单列表中使用它,每个表单都有一个提交删除按钮,它工作正常。

<script type="text/javascript">
    $('form').submit(function(e) {
        var currentForm = this;
        e.preventDefault();
        bootbox.confirm("Are you sure?", function(result) {
            if (result) {
                currentForm.submit();
            }
        });
    });
</script>
于 2013-09-20T09:14:18.117 回答
12

与往常一样:就在您提出问题后,您自己会找到答案:-)。请参阅此答案:https ://stackoverflow.com/a/2420806/219187 (另请注意答案中的评论)。

适应我的问题,解决方案如下:

$('#myForm').submit(function() {
    var currentForm = this;
    bootbox.confirm("Are you sure?", function(result) {
        if (result) {
            currentForm.submit();
        }
    });
});
于 2012-07-03T15:03:10.030 回答
1

这段代码非常适合我......

<script type="text/javascript">
$('#myForm').click(function(e) {
    e.preventDefault();
    var msg = 'Souhaitez vous vraiment supprimer ce produit ?';
    bootbox.confirm(msg, function(result) {
        if (result) {
            $('#myForm').submit();
        }
    });
});
</script>
于 2014-05-06T12:56:11.707 回答
1

您可以通过使用 .trigger() 方法将其他参数传递给提交处理程序来解决此问题:

$('form').submit(function (e, confirmed) {
    var currentForm = $(e.currentTarget);
    if (!confirmed) {
        e.preventDefault();
        bootbox.confirm("Are you sure?", function (result) {
            if (result) {
                currentForm.trigger('submit', { confirmed: true });
            }
        });
    }
});

首次提交表单时,'confirmed' 参数未定义并显示引导框对话框。如果用户确认对话框中的操作,则使用附加参数再次触发提交事件,并正常提交表单。

于 2019-10-11T11:03:06.123 回答
0

我的解决方案

@Html.ActionLink("Delete", "DeleteReport", new { id = item.Id }, new { @class = "btn btn-danger", onclick = String.Format("return ASE.ConfirmAction(this.href, 'Delete {0}?');", item.Name) })
var ASE = {
    ConfirmAction: function (href, text) {
        bootbox.confirm(text, function (result) {
            if (result)
                window.location = href;
        });

        return false;
    }
}
于 2014-08-28T09:42:46.390 回答