javascript - 在某些单选按钮选择条件下启用禁用的字段集

标签 javascript forms ecmascript-6

这是我想要实现的目标:

Remove disabled attribute from the baz fieldset only after both of these conditions are met:

  1. If one or two is checked.
  2. After any bar radio input is checked.

因此,如果选择了 two,则不要从任何 bar 之后的 baz 字段集中删除 disabled 属性输入已检查。

我知道如何解决上面列出的第一个条件,但不知道如何解决第二个条件。我错过了什么?

const form = document.forms[0]
const foo = form.elements.foo
const bazFieldset = form.querySelector("fieldset:last-of-type")

foo.forEach(foo => {
  foo.addEventListener("click", () => {
    if (foo.value != "three") {
      bazFieldset.disabled = false
    } else {
      bazFieldset.disabled = true
    }
  })
})
<form>
<fieldset>
  <label><input type=radio name=foo value=one>One</label>
  <label><input type=radio name=foo value=two>Two</label>
  <label><input type=radio name=foo value=three>Three</label>
</fieldset>

<fieldset>
  <label><input type=radio name=bar value=four>Four</label>
  <label><input type=radio name=bar value=five>Five</label>
  <label><input type=radio name=bar value=six>Six</label>
</fieldset>

<fieldset disabled>
  <label><input type=radio name=baz value=seven>Seven</label>
  <label><input type=radio name=baz value=eight>Eight</label>
  <label><input type=radio name=baz value=nine>Nine</label>
</fieldset>
</form>

最佳答案

我会将一个 change 监听器附加到容器,而不是为每个元素分配一个监听器,并使用一个辅助函数,该函数可以接受选择器字符串作为输入,并输出是否检查与该选择器匹配的元素:

const bazFieldset = document.querySelector("fieldset:last-of-type")
const isChecked = selectorStr => document.querySelector(selectorStr + ':checked');
document.forms[0].addEventListener('change', () => {
  const enabled = (
    (isChecked('[value="one"]') || isChecked('[value="two"]'))
    && isChecked('[name="bar"]')
  );
  bazFieldset.disabled = !enabled;
});
<form>
  <fieldset>
    <label><input type=radio name=foo value=one>One</label>
    <label><input type=radio name=foo value=two>Two</label>
    <label><input type=radio name=foo value=three>Three</label>
  </fieldset>

  <fieldset>
    <label><input type=radio name=bar value=four>Four</label>
    <label><input type=radio name=bar value=five>Five</label>
    <label><input type=radio name=bar value=six>Six</label>
  </fieldset>

  <fieldset disabled>
    <label><input type=radio name=baz value=seven>Seven</label>
    <label><input type=radio name=baz value=eight>Eight</label>
    <label><input type=radio name=baz value=nine>Nine</label>
  </fieldset>
</form>

关于javascript - 在某些单选按钮选择条件下启用禁用的字段集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997279/

相关文章:

javascript - 是否有可能在 Promise.all 中捕获所有被拒绝的 promise ?

javascript - Rapidmail 订阅表格在电子邮件订阅后重定向 - Mailchimp

php - Symfony 表单 |动态集合类型值

javascript - 在javascript中使用$访问对象的属性

javascript - 如何在同一页面上以html形式操作php函数?

php - 如何在具有多个 foreach 的表单中仅显示 1 个提交按钮

javascript - 如何在 V8 中优化访问时间的小型对象引用数组?

javascript - 控制台上出现 "[Report Only] Refused to load the font..."错误消息

javascript - 如何将变量固定为 JavaScript 中的元素属性?

javascript - 监视函数 sinon 返回的函数