将多个单选按钮值存储在数组Javascript中

法基

我想将测试答案存储在javascript数组中。我用for循环创建了50个问题,用户可以在4个单选按钮(答案)之间进行选择。如何将这些答案存储在数组中?

我的问题卡

<% for(var i = 0; i < test.questions.length; i++){%>
  <br>
    <div class="card">
      <div class="card-header">
        <%= test.questions[i].question%></h5>
      </div>
      <ul class="list-group list-group-flush" style="padding: 10px;">
          <li class="list-group-item"><input type="radio" name="one+<%=i%>" value="a"> <%= test.answers[0].answer%></li>
          <li class="list-group-item"><input type="radio"  name="one+<%=i%>" value="b"> <%= test.answers[1].answer%></li>
          <li class="list-group-item"> <input type="radio" name="one+<%=i%>" value="c"> <%= test.answers[2].answer%></li>
          <li class="list-group-item"><input type="radio" name="one+<%=i%>" value="d"> <%= test.answers[3].answer%></li>
          <li class="list-group-item"><input type="radio" name="one+<%=i%>" value="e"> <%= test.answers[4].answer%></li>
      </ul>
    </div>
  </div>
<%}%>

我尝试过的是:


<script>
  var arr = []
  document.getElementById("confirm").addEventListener("click", function() {
      for (let index = 0; index < 51; index++) {
      
      var buttonName = "one" + index
     
      var buttChecked = document.querySelector('[name=buttonName]:checked')
      
      if (buttChecked != null) {
        arr.push(buttChecked.value)
      }
      console.log(arr)
    }
  })

</script>
斯科特·马库斯(Scott Marcus)

只需在包含单选按钮组名称的数组上循环,并获取该组中所选按钮的值并添加到数组中:

// Store the names of the radio button sets
let names = ["one","two","three"]
let results = [];

document.querySelector("button").addEventListener("click", function(event){
  results = names.map(function(el){
    return document.querySelector("input[name='" + el + "']:checked").value;
  });
  
  console.log(results);
});
<div class="question">
 <input type="radio" name="one" value="Choice A">Something |
 <input type="radio" name="one" value="Choice B">Something |
 <input type="radio" name="one" value="Choice C">Something
</div>

<div class="question">
 <input type="radio" name="two" value="Choice A">Something |
 <input type="radio" name="two" value="Choice B">Something |
 <input type="radio" name="two" value="Choice C">Something 
</div>

<div class="question">
 <input type="radio" name="three" value="Choice A">Something |
 <input type="radio" name="three" value="Choice B">Something |
 <input type="radio" name="three" value="Choice C">Something
</div>
<br>
<button>Collect Answers</button>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章