Confirm form submission using bootbox.confirm()
我有一个表单,想拦截表单提交以使用Bootbox显示确认对话框。
如果用户点击
我尝试了这个:
1 2 3 | $('#myForm').submit(function() { return bootbox.confirm("Are you sure?"); }); |
但是,
然后,我注意到
那么确认表单提交的正确方法是什么?
我只能通过防止默认的表单行为来使此工作正常,这是下面的解决方案。
我在表单列表中使用了此表单,每个表单都有一个提交删除按钮,它工作正常。
1 2 3 4 5 6 7 8 9 10 | <script type="text/javascript"> $('form').submit(function(e) { var currentForm = this; e.preventDefault(); bootbox.confirm("Are you sure?", function(result) { if (result) { currentForm.submit(); } }); }); |
一如往常:在您提出问题之后,您就可以自己找到答案:-)。 请参阅以下答案:https://stackoverflow.com/a/2420806/219187(另请注意答案中的注释)。
适应我的问题,解决方案如下:
1 2 3 4 5 6 7 8 | $('#myForm').submit(function() { var currentForm = this; bootbox.confirm("Are you sure?", function(result) { if (result) { currentForm.submit(); } }); }); |
您可以通过使用.trigger()方法将其他参数传递给提交处理程序来解决此问题:
1 2 3 4 5 6 7 8 9 10 11 | $('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"参数是未定义的,并且会显示启动对话框。 如果用户在对话框中确认操作,则使用附加参数再次触发Submit事件,并且表单将正常提交。
这段代码非常适合我...
1 2 3 4 5 6 7 8 9 10 | <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(); } }); }); |
我的解决方案
1 | @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) }) |
1 2 3 4 5 6 7 8 9 10 | var ASE = { ConfirmAction: function (href, text) { bootbox.confirm(text, function (result) { if (result) window.location = href; }); return false; } } |