Search code examples
javascriptradio-buttonejsstorequeryselector

Store multiple radio button values in an array Javascript


I would like to store my test answers in an array in javascript. I created 50 questions with for loop, the user can choose between 4 radio buttons(answer). How could i store these answers in an array?

MY QUESTION CARDS

<% 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>
<%}%>

WHAT I TRIED:


<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>

Solution

  • Just use loop over an array containing the names of the radio button groups and get the value of the selected button in that group and add to the array:

    // 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>