Fasna Fasna - 4 years ago 314
Javascript Question

jQuery .push() not working

$('#create').click(function(){

var metaObj = {};
var dataObj = {};
var fields = [];
$('#tableform').find(".meta").each(function(){

metaObj[this.name] = this.value;
});

$('.datarow').each(function () {

$('td > input, select',this).each(function () {
dataObj[this.name] = this.value;

});
console.log(dataObj);
fields.push(dataObj);
});

console.log(JSON.stringify(metaObj));
console.log(JSON.stringify(fields));
});


I have a form inside table. Each row has same input fields. datarow is class name of each row. I traverse through every row to get the values.

console.log(dataObj);
shows every row of input. But, the fields array only the last object added 'n' times. n = number of rows.

Output at console is here:
enter image description here

Answer Source

You need to put var dataObj = {}; inside the each() code block, so that it is empty for the start of each .datarow iteration:

$('#create').click(function() {    
    var metaObj = {};
    var fields = [];

    $('#tableform').find(".meta").each(function(){    
        metaObj[this.name] = this.value;
    });

    $('.datarow').each(function () {
        var dataObj = {}; // move declaration here
        $('td > input, select',this).each(function () {
            dataObj[this.name] = this.value;    
        });
        console.log(dataObj);
        fields.push(dataObj);
    });

    console.log(JSON.stringify(metaObj));
    console.log(JSON.stringify(fields));
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download