Ovidiu G
Ovidiu G

Reputation: 1273

Can't push item into empty array

I have this function where when I click a button I loop over some divs and get the id of that div along with some checkbox inputs id's if they are marked. To store this values I have a dictionary which is suppose to store the items like this:

{
   1: [4,5],
   2: [2,3]
}

The keys represent the id's of each div and the values are the checkbox items id's that are clicked.

Full code:

$(document).on('click', '.trimite-rasp', function(){
    var formData = {}
    $.each($('.single-question'), function(){
        var listIds = [];
        var qId = $(this).attr('qid');
        console.log(qId);
        $.each($('.form-check-input'), function(){
            if($(this).is(':checked')){
                var thisId = ($(this).attr('aid'));
                $(listIds).push(thisId);
            }
        });

        formData[qId] = listIds;
    });
    console.log(formData);

});

The only problem here is that listIds array is always empty. I can't push the values to that array, and I'm sure the checkbox id is correct because I console.log it and it's taken correctly.

Upvotes: 1

Views: 1374

Answers (2)

Rafeeq Mohamed
Rafeeq Mohamed

Reputation: 190

Try this

listIds.push(thisId);

Upvotes: 0

Eddie
Eddie

Reputation: 26844

It is because you are using the array as a jQuery selector

use

var thisId = $(this).attr('aid'); 
listIds.push(thisId);

instead of

 $(listIds).push(thisId);

Upvotes: 3

Related Questions