如何使用单选按钮,其中每个按钮专用于一个数组值?

How can I use radio button where each button is dedicated to one array value?

所以我想做的是创建一个单选按钮,比如 5 个选项。因为它是一个单选按钮,显然只能 selected 一个选项。我希望这个数组按钮将五个值插入一个数组,其中 selected 给出值 1,其他值 0.

假设我有五个选项:A、B、C、D、E

<form method="POST">
  <input type="radio" id="html" name="fav_language" value="1">A<br>
  <input type="radio" id="html" name="fav_language" value="1">B<br>
  <input type="radio" id="html" name="fav_language" value="1">C<br>
  <input type="radio" id="html" name="fav_language" value="1">D<br>
  <input type="radio" id="html" name="fav_language" value="1">E<br>
<button type="submit" value="Submit">Submit</button>
</form>

如果select选项B,我怎样才能把它放在一个数组中,使其等于[0,1,0,0,0]。 有没有简单的方法可以做到这一点? 非常感谢

  1. 向表单提交添加一个 eventListener
  2. 将 querySelectorAll 转换为数组并映射已检查属性的真实性

document.getElementById("myForm").addEventListener("submit", function(e) {
  e.preventDefault(); // remove if you want the form to submit
  const arr = [...document.querySelectorAll("[name=fav_language]")]
    .map(rad => +rad.checked);
  console.log(arr)
})
<form method="POST" id="myForm">
  <input type="radio" id="html" name="fav_language" value="1">A<br>
  <input type="radio" id="html" name="fav_language" value="1">B<br>
  <input type="radio" id="html" name="fav_language" value="1">C<br>
  <input type="radio" id="html" name="fav_language" value="1">D<br>
  <input type="radio" id="html" name="fav_language" value="1">E<br>
  <button type="submit" value="Submit">Submit</button>
</form>

在按下按钮时执行的表单中添加了一个 onSubmit 函数。该函数然后根据用户选择的选项分配数组中的值。

let arr = [];
const createArray = (e) => {
  radios = document.getElementsByName("fav_language");
  for (var i = 0, length = radios.length; i < length; i++) {
    arr[i] = +radios[i].checked;
  }
  console.log(arr);
}
<form method="POST" onsubmit="createArray()">
  <input type="radio" id="html" name="fav_language" value="1">A<br>
  <input type="radio" id="html" name="fav_language" value="1">B<br>
  <input type="radio" id="html" name="fav_language" value="1">C<br>
  <input type="radio" id="html" name="fav_language" value="1">D<br>
  <input type="radio" id="html" name="fav_language" value="1">E<br>
  <button type="submit" value="Submit">Submit</button>
</form>