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

如何让提交按钮仅在复选框勾选后再跳转至目标链接

问题根源
  • 事件绑定位置错误:onsubmit 是<form>标签的专属事件,你错误将其绑定到了复选框<input>上,校验逻辑完全不会触发
  • 缺少表单元素标识:校验逻辑中通过form.terms.checked读取复选框状态,但复选框未设置name="terms"属性,无法通过表单对象直接获取到该元素
  • 提交与校验逻辑分离:你给提交按钮单独绑定了点击跳转事件,该事件不会触发校验逻辑,点击后会直接执行跳转操作
修复方案

你可以选择以下任意一种方式修改代码:

方案1:使用表单默认提交逻辑(推荐)

修正后HTML代码

<form class="n-chk" style="margin-bottom:1em ;text-align:center;" onsubmit="return checkForm(this);">
  <label class="new-control new-checkbox checkbox-primary">
    <input name="terms" type="checkbox" required  >
    <span class="new-control-indicator"></span>
    <span class="text-dark"> 我已阅读并同意
    <a href="#" target="_blank" class="text-primary px-1" style="text-decoration: none;">使用条款</a> 及
    <a href="#" target="_blank" class="text-primary px-1" style="text-decoration: none;">隐私政策</a>
    </span>
    </label>
  <input type="submit" id="submitBtn" class="btn btn-primary" data-bs-toggle="button" autocomplete="off" value="支付">
</form>

修正后JS代码

function checkForm(form) {
  if (!form.terms.checked) {
    alert("请先勾选同意使用条款和隐私政策");
    form.terms.focus();
    // 校验不通过,阻止表单提交
    return false;
  }
  // 校验通过执行跳转
  window.location.href = "替换为你需要跳转的目标地址";
  // 阻止表单默认提交行为
  return false;
}

方案2:保留按钮单独绑定点击事件的写法

修正后JS代码

function checkForm() {
  const terms = document.querySelector('input[name="terms"]');
  if (!terms.checked) {
    alert("请先勾选同意使用条款和隐私政策");
    terms.focus();
    return false;
  }
  return true;
}
const pay = document.getElementById("submitBtn");
pay.addEventListener("click", myFunction);

function myFunction(e) {
  // 先阻止按钮默认的表单提交行为
  e.preventDefault();
  // 校验通过后再执行跳转
  if(checkForm()) {
    window.location.href = "替换为你需要跳转的目标地址"
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 15:27:02