1
I’m having a hard time trying to create a dynamic associative array within a loop, the error returned in the console is Cannot read property 'push' of undefined
, the idea is a sports quiz with 3 questions for each team, I’m using the attribute "data-time"
which is equal in the 3 inputs of this team, so when sending the result an array would be created with the team name being the key and its "child arrays" would be the answers.
Example of inputs:
<input type="radio" name="respota1" value="respota1" data-time="flamengo">
<input type="radio" name="respota2" value="respota2" data-time="flamengo">
<input type="radio" name="respota3" value="respota3" data-time="flamengo">
Jquery:
var answers = $("input[data-time]:checked");
var items = new Array();
$.each( answers, function( key, value ) {
var time = $(this).attr('data-time');
switch(time) {
case 'flamengo':
items['flamengo'].push($(this).val());
break;
}
});
console.log(items);
How to proceed?
I understood, but in the case there are really 3 different numbers, the idea is to capture the 3 values and insert into the items arrays, the key being the name of the type
– Thiago
Oh yes. So it’s the same thing I did in the answer. It will take what is checked and insert into the array.
– Sam
He created numerical arrays and inside them the value of the team, the ideal would be like this: [ { "flamengo": { "answer1", "answer2", "answer3" } ;]
– Thiago
When I add another team a new case, it returns: Cannot read Property 'push' of Undefined
– Thiago
equal to those that exist, only that the "data-time" would be another, for example, data-time=""
– Thiago
Let’s go continue this discussion in chat.
– Thiago
Updated response.
– Sam