晚上好,我在过go 的几天里一直在试图弄清楚如何在Java脚本中验证多个广播组.我的目标是确定用户是否进行了 Select ;如果没有,则通过错误消息提示他们.

我翻遍了Stack和谷歌等网站,但无论我try 或找到什么,我似乎就是找不到我想要的行为.到目前为止,我找到的问题/资源已经 bootstrap 我找到了我现在的例子(如下所示),但我希望你们中的一个可爱的人能 bootstrap 我越过终点线.

具体地说,我正在寻找一个如何验证所有单播组的示例,以确保用户已经在每个组中进行了 Select .(我希望每个步骤都有好的注释和解释,因为循环对我来说很难理解.)

Thanks in advance. ????????

我在下面附上了一个完整的代码片段,里面有我的工作内容;我已经调整了这个代码片段,go 掉了所有不必要的东西,希望它更容易理解.

EDIT:个 忘记提及以下代码的问题.下面的代码似乎在某些 Select 组合上进行了验证,但在其他 Select 组合上失败了,我怀疑这可能是循环错误,但当我认为我不能很好地理解它们时,我承认.

EDIT:个 对于那些即将到来的人,我已经接受了@KooiInc.的答案,因为它回答了这个问题.虽然Jojo先生是正确的,但我应该使用表单和HTML5进行验证.愚蠢的疏忽最终让我浪费了一吨时间.????啊,嗯,这都是一次学习的经历.????????

Example Snippet

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();
* {
  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;
}
<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 Select 器来确定单选状态.下面是一个最小的例子:

document.addEventListener(`click`, evt => {
  if (evt.target.id === `allchecked`) {
    console.clear();
    const bothChecked = document
      .querySelectorAll(`.rGroup input[type='radio']:checked`)
      .length === 2;
    console.log(`both groups checked? ${
      bothChecked ? `Yep`: `Nope`}`);
  }
})
<div class="rGroup" id="group1">
  <input type="radio" name="rg1"> one
  <input type="radio" name="rg1"> two
  <input type="radio" name="rg1"> three
</div>
<div class="rGroup" id="group2">
  <input type="radio" name="rg2"> one
  <input type="radio" name="rg2"> two
  <input type="radio" name="rg2"> three
</div>
<button id="allchecked">both checked?</button>

Javascript相关问答推荐

拖放仅通过 Select 上传

在react js中使用react—router—dom中的Link组件,分配的右侧不能被 destruct ''

使用useEffect,axios和useParams进行react测试

屏幕右侧屏障上的产卵点""

无法从NextJS组件传递函数作为参数'

如何迭代叔父元素的子HTML元素

WhatsApp Cloud API上载问题:由于MIME类型不正确而导致接收&Quot;INVALID_REQUEST";错误

未加载css colored颜色 ,无法将div设置为可见和不可见

自定义确认组件未在vue.js的v菜单内打开

使用父标签中的Find函数查找元素

在Odoo中如何以编程方式在POS中添加产品

当我点击一个按钮后按回车键时,如何阻止它再次被点击

将Auth0用户对象存储在nextjs类型脚本的Reaction上下文中

FireBase FiRestore安全规则-嵌套对象的MapDiff

为什么NULL不能在构造函数的.Prototype中工作

使用可配置项目创建网格

无法向甜甜圈图表上的ChartJSImage添加可见标签

我如何才能让p5.js在不使用实例模式的情况下工作?

如何在单击链接时设置一个JavaScript变量(以打开弹出窗口的特定部分)

响应,Use Callback更新状态变量,该变量也存在于其依赖数组中,它如何防止无限重新呈现?