使用自定义模型弹出确认表单提交

Confirming a form submission with a custom model popup

本文关键字:确认 表单提交 模型 自定义      更新时间:2023-09-26

我的应用程序中有一些删除表单,我想在提交前用javascript/jQuery确认。

简单的方法是这样做:

$('form.confirm-form').submit(function(){
    return confirm('Are you sure?');
});

会弹出一个浏览器自带的确认框,只有当用户单击OK时才提交表单。

对于更漂亮的东西,我想我使用Bootstrap模式进行确认,并为此检查了Bootbox.js库。

我似乎不能让它正常工作,因为它需要一个回调,不阻止表单提交。我用preventDefault来阻止表单过早提交但是现在

  1. 我不能用取消按钮取消模式,
  2. OK按钮提交表单失败。

下面是我的代码:

$('form.confirm-form').submit(function(event) {
    event.preventDefault();
    bootbox.confirm("Are you sure?", function(result){
        return result;
    });
});

我如何用这个库复制本机confirm的行为?

我在一个创建表单上挣扎,解决方案实际上很容易,根本不需要任何JavaScript(如果你已经在使用JQuery和Bootstrap)。

你所需要做的就是将提交按钮(button type="submit")更改为触发Boostrap模式的通用按钮(button type="button")。更多关于按钮动作的信息:https://stackoverflow.com/a/9643866.

然后让Boostrap模式中的按钮实际提交表单。如果你把你的模态HTML保存在表单中,你不需要写一行JS。

JS Bin: https://jsbin.com/lulipubafo/edit?html,output

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
  <title>JS Bin</title>
</head>
<body>
<form action="/page" method="post">
  <input type="text" name="first_name">
  <button type="button" class="btn btn-default" data-toggle="modal" data-target="#confirm-submit">Submit</button>
  <div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h2 class="modal-title">Confirm</h2>
        </div>
        <div class="modal-body">
          <p>Are you sure you want to submit?</p>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-success">Yes, Submit</button>
          <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
        </div>
      </div>
    </div>
  </div>
</form>
</body>
</html>

试试这个

$('form.confirm-form').submit(function(event) {
    var currentForm = this;
    event.preventDefault();
    bootbox.confirm("Are you sure?", function(result){
        if(result)
         {
   currentForm.submit()
         }
    });
});