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

表单提交时未选中单选按钮,如何获取对应错误代码?

表单提交时处理未选中单选按钮的错误触发需求

需求

表单提交时,若未选中任何单选按钮,需触发指定的错误;当前可正常获取选中单选按钮的值,但未选中时仅会在控制台出现未捕获错误,无法主动触发预期的错误逻辑。

原始代码

HTML

<form action="/" id="RatingForm">
  <input type="radio" name="rating" id="btn-1" value="1" />
  <label for="btn-1">1</label>
  <input type="radio" name="rating" id="btn-2" value="2" />
  <label for="btn-2">2</label>
  <input type="radio" name="rating" id="btn-3" value="3" />
  <label for="btn-3">3</label>
  <input type="radio" name="rating" id="btn-4" value="4" />
  <label for="btn-4">4</label>
  <input type="radio" name="rating" id="btn-5" value="5" />
  <label for="btn-5">5</label>
  <input type="submit" name="" id="submit" />
</form>

JavaScript

const form = document.getElementById("RatingForm");
form.addEventListener("submit", (e) => {
  e.preventDefault();
  let button = document.querySelector("input:checked");
  if (button.value !== 0) {
    console.log(button);
  } else {
    console.log("error");
  }
});

问题根源

当没有单选按钮被选中时,document.querySelector("input:checked")返回null,此时直接访问button.value会抛出Cannot read properties of null (reading 'value')的未捕获错误,导致后续错误逻辑无法执行。

解决方法

先判断选中的单选按钮是否存在,再执行对应逻辑:

方案1:主动抛出指定错误

如果需要严格复现控制台的错误信息,可主动抛出对应类型的错误:

const form = document.getElementById("RatingForm");
form.addEventListener("submit", (e) => {
  e.preventDefault();
  const button = document.querySelector("input[name='rating']:checked");
  // 先检查是否有选中的按钮
  if (!button) {
    throw new TypeError("Cannot read properties of null (reading 'value')");
  }
  // 选中时的处理逻辑
  console.log(button);
});

方案2:自定义错误处理

若不需要抛出原生错误,而是执行自定义提示或逻辑:

const form = document.getElementById("RatingForm");
form.addEventListener("submit", (e) => {
  e.preventDefault();
  const button = document.querySelector("input[name='rating']:checked");
  if (button) {
    console.log(button);
  } else {
    // 自定义错误操作,比如提示用户
    console.error("请选择一个评分");
    // 也可结合DOM显示错误提示
    // document.getElementById("errorMsg").textContent = "必须选择一个评分";
  }
});

提示

使用input[name='rating']:checked可以更精准地定位到目标单选按钮,避免页面中其他选中的input干扰判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:20:28