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

如何验证多个单选按钮组中每组均有选项被选中?

求助:JavaScript验证多个单选按钮组

大家晚上好,我最近几天一直在尝试用JavaScript验证多个单选按钮组,想要判断用户是否已做出选择;如果没有选择,则通过错误消息提示他们。

我已经在Stack和Google等平台查找过资料,但无论尝试什么方法,都无法实现预期的效果。目前的示例代码是根据找到的问题和资料编写的,但希望有人能帮我完成最终的实现。

我具体需要的是一个验证所有单选按钮组的示例,确保用户在每组中都做出了选择。(希望代码带有详细注释和步骤说明,因为我对循环的理解还比较困难。)

提前感谢大家。😅👌

下面附上我整理的完整代码片段,我剔除了所有非必要内容,以便更容易理解。

编辑补充

  • 忘记说明现有代码的问题了。下面的代码在某些选择组合下能正常验证,但在另一些组合下会失效,我怀疑是循环错误,但我承认自己对循环的理解还不够深入。
  • 给后续看到的人说明一下,我采纳了@KooiInc的答案,因为它解决了我的问题。不过Mister Jojo说得对,我应该使用表单和HTML5进行验证,这个疏忽让我浪费了大量时间。😅 不过,这都是学习的过程。👍👌

示例代码片段

HTML代码

<div class="radioGroup">
  <div class="radioOption">
    <input type="radio" id="radioOne" name="group_one" value="Foo">
    <label for="radioOne">My Foo Radio</label>
  </div>
  <div class="radioOption">
    <input type="radio" id="radioTwo" name="group_one" value="Bar">
    <label for="radioTwo">My Bar Radio</label>
  </div>
</div>

<div class="radioGroup">
  <div class="radioOption">
    <input type="radio" id="radioThree" name="group_two" value="Baz">
    <label for="radioThree">My Baz Radio</label>
  </div>
  <div class="radioOption">
    <input type="radio" id="radioFour" name="group_two" value="Qux">
    <label for="radioFour">My Qux Radio</label>
  </div>
</div>

<div class="btn">
  <input type="button" data-direction="next" value="Next" />
</div>

<div id="errors"> Testing! </div>

CSS代码

* {
  text-align: center;
  box-sizing: border-box;
  font-family: -apple-system, BlinkMacSystemFont, Arial, sans-serif;
}

.radioGroup {
  display: flex;
  justify-content: center;
  align-items: center;
  /* flex-flow: row nowrap; */
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: space-between;
  gap: 1em;
  max-width: 640px;
  margin: 0 auto;
}

.radioGroup:first-of-type {
  margin-top: 3em;
}

@media screen and (max-width: 768px) {
  flex-direction: column;
}

.radioOption {
  flex-grow: 1;
  width: 100%;
  margin-bottom: 1em;
}

input[type="radio"] {
  position: absolute;
  left: -9999px;
  opacity: 0;
  z-index: 100;
}

label {
  display: block;
  padding: 0.5em 1em;
  border: 1px solid #999;
  color: #999;
  width: 100%;
  cursor: pointer;
  transition: all 0.2s ease;
}

input[type="radio"]:checked+label {
  border: 1px solid #000;
  color: #000;
  transition: all 0.2s ease;
}

input[type="button"] {
  margin-top: 3em;
  background-color: #ddd;
  border: none;
  color: #000;
  padding: 0.5em 2em;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
}

input[type="button"]:hover {
  background-color: #ccc;
}

#errors.invalid {
  display: block;
}

#errors {
  display: none;
  color: #842029;
  background-color: #f8d7da;
  border: 1px solid #f5c2c7;
  font-weight: bold;
  padding: 0.5em 2em;
  width: 300px;
  margin: 2em auto;
}

JavaScript代码

class radioChecks {

  // Constructor.
  constructor() {
    this.inputs = document.querySelectorAll("input");
    this.radioGroups = document.querySelectorAll(".radioGroup");
    this.errors = document.getElementById("errors");
    this.bindEvents();
  }

  // Bind Events.
  bindEvents() {
    for (let i = 0; i < this.inputs.length; i++) {
      this.inputs[i].addEventListener("click", function(e) {
        if (e.target.dataset.direction) {
          e.target.dataset.direction === "next"
          this.validate();
        }
      }.bind(this));
    }
  }

  validate() {
    const _this = this;

    function isRadioGroupValid() {
      let checked = false;
      let inputName = "";
      for (let i = 0; i < _this.radioGroups.length; i++) {
        const radios = _this.radioGroups[i].querySelectorAll('[type="radio"]');

        for (let j = 0; j < radios.length; j++) {
          radios[i].checked ? checked = true : checked = false;
          inputName = radios[i].name;
        }
      }

      !checked
        ?
        _this.errorHandler(_this, `Please select an option for ${inputName}.`, true) :
        _this.errorHandler(_this, "", false);

    }

    isRadioGroupValid();
    console.log("All radio groups have selection.");
    return true;
  }

  errorHandler(_this, message, error) {
    // Show any errors.
    function showErrors(message) {
      _this.errors.innerHTML = message;
      _this.errors.classList.add("invalid");
      throw new Error(message);
    }

    // Clear any existing errors.
    function clearErrors() {
      _this.errors.innerHTML = "";
      _this.errors.classList.remove("invalid");
    }

    // if error true. Show error.
    error ? showErrors(message) : clearErrors();
  }
}


new radioChecks();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:57:18