javascript - 按顺序启用表单中的字段集

标签 javascript html forms

当字段集具有 id 属性时,我知道如何启用序列中的下一个 fieldset:

function enableFieldset(element) {
  document.getElementById(element).disabled = false;
}
<fieldset id="foo" onchange="enableFieldset('bar', event)">
<label><input type="radio" name="foo">Apples</label>
<label><input type="radio" name="foo">Oranges</label>
</fieldset>

<fieldset id="bar" disabled>
<label><input type="radio" name="bar">Bus</label>
<label><input type="radio" name="bar">Airplane</label>
</fieldset>

…

我想以多步骤形式启用下一个同级fieldset,该形式没有设置id(通过使用.nextElementSibling或类似的),在当前fieldset中检查输入后。我还想将 JavaScript 与 HTML 代码分开(使用 addEventListener)。

最佳答案

您可以通过使用 document.querySelectorAll 选择所有字段集,将 change 事件监听器附加到所有字段集。这会将 JS 代码与 HTML 分开。

在事件处理程序中,您可以获取已禁用的下一个同级,并将其启用。为此,请使用 nextElementSibling

document.querySelectorAll('fieldset').forEach(fs => {
  fs.addEventListener('change', function() {
    var next = this.nextElementSibling;
    
    while (next && !next.disabled) {
      next = next.nextElementSibling;
    }
    
    if (next) {
      next.disabled = false;
    }
  });
})
<fieldset id="foo">
  <label><input type="radio" name="foo">Apples</label>
  <label><input type="radio" name="foo">Oranges</label>
</fieldset>

<fieldset id="bar" disabled>
  <label><input type="radio" name="bar">Bus</label>
  <label><input type="radio" name="bar">Airplane</label>
</fieldset>

<fieldset id="bar" disabled>
  <label><input type="radio" name="x">Bus1</label>
  <label><input type="radio" name="x">Airplane1</label>
</fieldset>

<fieldset id="bar" disabled>
  <label><input type="radio" name="y">Bus2</label>
  <label><input type="radio" name="y">Airplane2</label>
</fieldset>

关于javascript - 按顺序启用表单中的字段集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51897334/

相关文章:

php - 如何从标签中获取值

Javascript 如何从 URL 中提取 INT 形式的 ID?

javascript - 无法使用 JQuery 设置 Select2 下拉值

javascript - 是否可以使用 Object.assign 来克隆对象及其方法?

javascript - 使用javascript在网页中用<figure>包裹所有图像

php - <form> 标签在用 php 创建时不显示

javascript - 如何通过已经建立的Websocket连接发送Websocket消息?

javascript - 填充 3 个动态下拉菜单

html - 使用 HTML 和 CSS 创建的网页上的额外空间

python - Django 选择表单字段的标签