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>

39 thoughts on “Store multiple radio button values in an array Javascript”

  1. 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>
    Reply
  2. With Handlebars JS, you can set up a question/answer data structure and navigate between questions, pre-selecting the answer.

    const randomSort = arr => arr.sort(() => 0.5 - Math.random());
    const mod = (n, m) => ((n % m) + m) % m;
    const bump = (count, index, amount) => mod(index + amount, count);
    
    // Handlebars helpers
    Handlebars.registerHelper({
      ifEquals: function(arg1, arg2, options) {
        return arg1 === arg2 ? options.fn(this) : options.inverse(this);
      },
      randomEach: function(array, opts) {
        if (opts.data) data = Handlebars.createFrame(opts.data);
        return randomSort(array).map((e, i) => {
          if (data) data.index = i;
          return opts.fn(e, { data });
        }).join('');
      }
    });
    
    const compileTemplate = (selector) =>
      Handlebars.compile(document.querySelector(selector).innerHTML);
      
    const questions = [{
      prompt: "Which fruit is yellow?",
      answers: [ "Apple", "Banana", "Cantaloupe", "Date" ],
      answer: "Banana"
    }, {
      prompt: "Which vegetable is red?",
      answers: [ "Carrot", "Pea", "Potato", "Tomato" ],
      answer: "Tomato"
    }];
    
    // Buttons
    const prevBtn = document.querySelector('#controls > .prev-btn');
    const nextBtn = document.querySelector('#controls > .next-btn');
    
    let currQuestion = 0;
    
    const main = () => {
      rerender();
      prevBtn.addEventListener('click', handlePrev);
      nextBtn.addEventListener('click', handleNext);
    };
    
    // Templates
    const questionTemplate = compileTemplate('#question-template');
    const infoTemplate = compileTemplate('#info-template');
    
    // Rendering contexts
    const questionEl = document.querySelector('#question');
    const infoEl = document.querySelector('#info');
    
    const navigateQuestion = (amount) => {
      currQuestion = bump(questions.length, currQuestion, amount);
    };
    
    const handlePrev = () => {
      navigateQuestion(-1);
      rerender();
    };
    
    const handleNext = () => {
      navigateQuestion(-1);
      rerender();
    };
    
    const renderQuestion = (question) => {
      questionEl.innerHTML = questionTemplate(question);
      infoEl.innerHTML = infoTemplate({
        page: currQuestion + 1,
        count: questions.length
      });
    };
    
    const rerender = () =>
      renderQuestion(questions[currQuestion]);
    
    main();
    .answer-field {
      display: block;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>
    <script id="question-template" type="text/x-handlebars-template">
      <h2>{{prompt}}</h2>
      <form>
      {{#randomEach answers}}
        <div class="answer-field">
          <input
            type="radio"
            id="answer-{{@index}}"
            name="contact"
            value="{{.}}"
            {{#ifEquals . ../answer}}checked{{/ifEquals}}
          >
          <label for="answer-{{@index}}">{{.}}</label>
        </div>
      {{/randomEach}}
      </form>
    </script>
    <script id="info-template" type="text/x-handlebars-template">
      <p>Question {{page}} of {{count}}</p>
    </script>
    <div id="question"></div>
    <div id="info"></div>
    <div id="controls">
      <button class="prev-btn">Prev</button>
      <button class="next-btn">Next</button>
    </div>
    Reply
  3. community action partnership idaho positive adjectives beginning with z to describe a person , community acquired pneumonia soap note. community cast chevy chase buy pregabalin lyrica medication , community advocates and support services community bank muscatine community biology ecosystems , social learning theory definition positive feedback biology definition? positive correlation cause and effect positive words vs negative words, community mobilization synonym community america telephone number.
    community bible church rockford il , environments toys followers on instagram environments cannot be coerced to other types.

    Reply
  4. office software open source drawing program website to buy Autocad software software programs for office suite. office suite for mac catalina 2020 software development conferences engeeeneringu#$sssaunnplus , wezone 8009 software download 2020. office software ipad free, hp officejet pro 8600 software for mac bio office software free download basler 2020 software download. office use software free download office software free open source, essential software for pc 2020.

    Reply

Leave a Comment