PeteTheGreek PeteTheGreek - 16 days ago 5
Javascript Question

javascript push() not working as anticipated

I'd like to add some checkbox info to an array before sending it off to a ajax post, but when it loops thru the checkboxes it seems to increment the number of items in the array but makes every entry in the array the same content. Here's my code.

var aData = [];
var item = [];
$(".providers_chk").each(function (index, element) {
if ($(this).attr("checked")) {
item[0] = element.value;
item[1] = element.name;
aData.push(item);
console.log(aData);
}
});


The array ends up looking like {"foo","bar"} for each entry, instead of {"foo","bar"} , {"foo1","bar1"} , {"foo2","bar2} etc

Answer

In your code you use only one array for pushing, which gets for every loop new values. At the end, and while the reference to the same object is spreaded over the result array, you get the same values in all pushed arrays.

You could create arrays on the fly, which are not linked by reference together.

var aData = [];
$(".providers_chk").each(function (index, element) {
    if ($(this).attr("checked")) {
        aData.push([element.value, element.name]);
        console.log(aData);
    }
});