You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap 4表单验证成功后显示成功模态框问题

解决Bootstrap 4表单验证后显示成功模态框的问题

嘿,我来帮你搞定这个问题!你怀疑event.showModal的写法有问题是完全正确的——这个方法是针对HTML5原生<dialog>元素的,和Bootstrap的模态框组件不兼容,而且你的表单代码里还有个小拼写错误,咱们一步步来修正:

第一步:修正表单的提交按钮

你的代码里按钮的type属性拼写错了,把type="submi"改成type="submit",不然表单没法正常触发提交事件。

第二步:添加Bootstrap成功模态框的HTML

在页面里加入模态框的结构,放在表单外面即可:

<!-- 成功提示模态框 -->
<div class="modal fade" id="successModal" tabindex="-1" role="dialog" aria-labelledby="successModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="successModalLabel">提交成功!</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        你的表单已经成功提交,我们会尽快联系你!
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>

第三步:编写正确的表单验证&模态框触发代码

替换你原来的JavaScript代码,用Bootstrap官方推荐的表单验证逻辑,验证通过后触发模态框:

// 监听表单提交事件
document.getElementById('form').addEventListener('submit', function(event) {
  // 阻止表单默认提交行为(避免页面刷新)
  event.preventDefault();
  
  // 检查表单是否通过Bootstrap的验证
  if (!this.checkValidity()) {
    // 如果验证不通过,触发Bootstrap的错误提示样式
    event.stopPropagation();
    this.classList.add('was-validated');
  } else {
    // 验证通过,显示成功模态框
    $('#successModal').modal('show');
    
    // 这里可以添加表单数据提交的逻辑(比如AJAX发送数据)
    // 示例:
    // fetch('你的提交接口', {
    //   method: 'POST',
    //   body: new FormData(this)
    // }).then(response => {
    //   // 处理提交后的逻辑
    // });
  }
});

// 初始化Bootstrap的实时表单验证(可选)
(function() {
  'use strict';
  window.addEventListener('load', function() {
    var forms = document.getElementsByClassName('needs-validation');
    Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('input', function() {
        if (form.checkValidity()) {
          form.classList.remove('was-validated');
        }
      }, false);
    });
  }, false);
})();

关键说明

  • 为什么不用event.showModal?:Bootstrap的模态框是基于jQuery和自定义JS实现的,必须用$('#modalId').modal('show')方法来触发显示,原生的showModal()对它无效。
  • 表单验证逻辑:Bootstrap 4的needs-validation类配合was-validated类来触发错误提示,我们通过checkValidity()方法判断表单是否验证通过。
  • 依赖注意:确保你的页面已经正确引入了jQuery、Popper.js和Bootstrap 4的JS文件(Bootstrap 4依赖这两个库)。

这样修改后,表单验证通过后就能正常弹出成功模态框啦!

内容的提问来源于stack exchange,提问作者Preston Crouse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:55:13