0

I know this question has been asked before but even though they didn't answer my question. i have a Json Array like below

[
  {
    "Item1": "Orange",
    "Item2": 40
  },
  {
    "Item1": "Banana",
    "Item2": 60
  },
  {
    "Item1": "Lemon",
    "Item2": 30
  }
]

I do a iteration through it using Jquery

$.each(details, function (index, jsonObject) {                                        
var k = index;
var ProductName = jsonObject.Item1;
var ProductPrice = jsonObject.Item2;
trHtml = '<tr>'
+ '<td style="padding: 5px 10px;">' + k + '</td>'
+ '<td style="padding: 5px 10px;">' + ProductName + '</td>'
+ '<td style="padding: 5px 10px;">' + ProductPrice + '</td>'
+ '</tr>'                                          
});

But the above code always appending the last row in the array?

Note: All previous duplicate of this question said declare your item name using var but it didn't helped me!

$(function() {
  var details = [];
  details = [{
      "Item1": "Orange",
      "Item2": 40
    },
    {
      "Item1": "Banana",
      "Item2": 60
    },
    {
      "Item1": "Lemon",
      "Item2": 30
    }
  ]

  $.each(details, function(index, jsonObject) {
    var k = index;
    var ProductName = jsonObject.Item1;
    var ProductPrice = jsonObject.Item2;
    trHtml = '<tr>' +
      '<td style="padding: 5px 10px;">' + k + '</td>' +
      '<td style="padding: 5px 10px;">' + ProductName + '</td>' +
      '<td style="padding: 5px 10px;">' + ProductPrice + '</td>' +
      '</tr>'
  });

  $("#classTable tbody").append(trHtml);
  $('#classModal').css('display', 'block');
  $('#classModal').modal('show');

})
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" type="text/css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js" type="text/javascript"></script>

<div id="classModal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="classInfo" aria-hidden="true" style="display:none;">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
          ×
        </button>
        <h4 class="modal-title" id="classModalLabel">
          Purchase Info
        </h4>
      </div>
      <div class="modal-body">
        <table id="classTable" class="table table-bordered">
          <thead>
            <tr>
              <th>NO.</th>
              <th>Product</th>
              <th>Price</th>
            </tr>
          </thead>
          <tbody>

          </tbody>
        </table>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">
          Close
        </button>
      </div>
    </div>
  </div>
</div>

0 Answers0