I have the following loop that adds an object to an array if certain criteria are met.
var form = $('form[id^="product-form"]'),
submit_button = $('#add-to-cart'),
attr_fields = $('.additional input[type=text]'),
attr_fields_default = {};
// Get the default values for each attribute field and place into an obj
attr_fields.each(function () {
var field = $(this),
field_id = field.attr('id'),
field_val = field.val();
attr_fields_default[field_id] = field_val;
});
var extra_attr = [];
for (var i = 0; i < attr_fields.length; i++) {
var _field = $(attr_fields[i]);
if (_field.val() != attr_fields_default[_field.attr('id')]) {
var jsonStr = {
'add': _field.attr('id'),
'quantity': 1
};
extra_attr.push(jsonStr);
console.log(jsonStr);
} else {
_field.attr('disabled', 'disabled').val('None');
}
}
console.log(extra_attr);
The code works perfectly until the last loop, although console.log( jsonStr ) outputs the last object as expected, console.log( extra_attr ) does not. It does not push the last item into the array. I even tried changing jsonStr to a dummy string ‘test’ and i still get the same result.
Here is a screenshot of my chrome developer console http://cl.ly/GdHw
I should also note that I originally tried to use .each() to loop through the selectors with the exact same results
attr_fields
.each(function(){
if ( $(this).val() != attr_fields_default[ $(this).attr('id') ] ) {
var jsonStr = {'add': $(this).attr('id'), 'quantity': 1};
extra_attr.push( jsonStr );
console.log( jsonStr );
} else {
$(this).attr('disabled', 'disabled').val('None');
}
The problem was with an asynchronous call later in the code that was using .pop() to grab the last element