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

表单字段验证通过后无法提交跳转的jQuery代码补全咨询

表单验证通过后无法提交跳转的解决方案

问题原因

你的原生校验逻辑本身没有问题,仅在校验失败时会阻止提交,校验通过时默认会走表单提交跳转。无法跳转是两个配置错误导致的:

  • 表单字段<textarea>缺少required必填校验属性,校验规则不生效;同时缺少name属性,就算提交后端也无法接收字段值
  • 若你之前打开了注释里的$(this).trigger('submit')代码,会导致提交事件反复触发死循环,也会阻止正常跳转

修正后代码

原生JS代码(无需额外引入jQuery)

(function() {
    window.addEventListener('load', function() {
        var forms = document.getElementsByClassName('needs-validation');
        Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                    // 此处不要触发submit事件,会导致死循环
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();

HTML代码(补全字段属性)

<form class="needs-validation" action="save.php" method="post" id="form" name="form" novalidate>
  <div class="row">
    <div class="col">
      <div class="mb-3">
        <label class="form-label" for="exampleFormControlInput20">Info</label>
        <!-- 补全必填标识required和字段名name,校验和提交才能正常生效 -->
        <textarea class="form-control" id="exampleFormControlTextarea25" name="user_info" rows="3" placeholder="请填写信息" required></textarea>
        <div class="invalid-tooltip">此字段为必填项</div>
      </div>
    </div>
  </div>

  <div class="card-footer text-end">
    <div class="col-sm-9 offset-sm-3">
      <button class="btn btn-success active" type="submit" title="提交信息">提交</button>
      <button class="btn btn-danger active" type="reset" title="取消">取消</button>
    </div>
  </div>
</form>

效果说明

修改完成后:

  • 空字段点击提交会触发校验提示,不会跳转
  • 字段填写完整校验通过后,表单会自动提交到save.php并完成跳转,不需要额外补充jQuery代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:54:02