0

I am having an issue with this function. When I am pushing objects into the array it is OK, but when I am retrieving stored objects I have the same value in every object.

function saveDetails() {
  var details = [];
  var productDetails = {};
  var id = $('#ddlDeliveryBoy option:selected').val();
  var count = $('#tbCustomer tbody tr').length;
  for (var index = 0; index < count; index++) {
    var tr = $('#tbCustomer tbody tr')[index];
    var countTD = $(tr).children('td').length - 4;
    for (var j = 3; j < (countTD + 4); j++) {
      var td = $(tr).children('td')[j];
      var txt = $(td).find('input[type="text"]');
      if ($.isNumeric(txt.val())) {
        productDetails.CustomerID = $(tr).data('id');
        productDetails.ProductID = $(td).data('id');
        productDetails.Quantity = parseFloat(txt.val()).toFixed(2);
        details.push(productDetails);
      }
    }
  }
  console.log(details);
}
Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
Neeraj Pathak
  • 759
  • 4
  • 13

1 Answers1

2

You need to move productDetails initialization inside if loop. Here is the code.

function saveDetails() {
  var details = [];
  var id = $('#ddlDeliveryBoy option:selected').val();
  var count = $('#tbCustomer tbody tr').length;
  for (var index = 0; index < count; index++) {
    var tr = $('#tbCustomer tbody tr')[index];
    var countTD = $(tr).children('td').length - 4;
    for (var j = 3; j < (countTD + 4); j++) {
      var td = $(tr).children('td')[j];
      var txt = $(td).find('input[type="text"]');
      if ($.isNumeric(txt.val())) {
        let productDetails = {};
        productDetails.CustomerID = $(tr).data('id');
        productDetails.ProductID = $(td).data('id');
        productDetails.Quantity = parseFloat(txt.val()).toFixed(2);
        details.push(productDetails);
      }
    }
  }
  console.log(details);
}
Raj
  • 505
  • 1
  • 6
  • 14