Zauber Zauber - 1 month ago 12
Javascript Question

How to loop through radio/checkbox inputs and push the id of selected ones to arrays

I've built a multiple choice quiz. Some answers have radio boxes, others have checkboxes as there are multiple correct answers. I have previously used a script to get the id of all of the :checked inputs and put them in an array to send to the server for assessment.

The array looked like this:

userAnswers = [ '1c', '2d', '3a', '3b', '3c', '3d', '4b', '5c', '5d', '6d' ]


I've managed to quite easily loop through all of the :checked inputs and add their html id to an array, but I need to change my data structure so it's easier to assess the answers on the server.

I'm trying to change the data structure to the following:

answers = [
['c'], // Question 1 answers
['d'], // Question 2 answers
['a', 'b', 'c', 'd'], // 3
['b'], // 4
['c', 'd'], // 5
['d'], // 6
]


To do this, I'm trying to create a loop that finds all :checked inputs based on their [data-question-number] value, then adds their html ID to an array, then adds that array to an array like above.

So far the closest I have got is the following:

let numberOfQuestions = Assessments.findOne().numQuestions; //returns the number of questions in the quiz e.g '25'
let selectedAnswers = [];

for(let i = 1; i <= numberOfQuestions; i++) {
let answers = $("input[data-question-number=" + i + "]:checked").attr('id');
}


This almost works, except the problem is that .attr() only returns the first attribute that matches, so in some of my questions where there are 4 checkboxes and the user may have checked 3 of them, I'll only get the first one returned to me.

If someone could help me mofidy this so that it inserts the id of all :checked inputs that would be awesome. Thanks!

Answer
let answers = []
for(let i = 1; i <= numberOfQuestions; i++) {
    let temp = []
    $("input[data-question-number=" + i + "]:checked").each(function() {
       temp.push(this.id)
    });
    answers.push(temp)
}