Giridharan Giridharan - 3 months ago 16
jQuery Question

Displaying Table view dynamically using jquery

I have stuck with an issue of displaying data with appropriate format. Please guide me how to achieve of expected result in jquery

<script>
$(document).ready(function () {
var numbers = ['hamburger', 'Potato salad', 'Brocolli', 'Apple pie'];
var month = [2,3,6,5,4];
for(i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
$('#foodItem').append(numbers[i]);
$('#portionSize').append(month[i]);
}
});
</script>


html

<table> <tr>
th>Food Item</th>
<th>Portion Size</th>
</tr>
<td id="foodItem">
</td>
<td id="portionSize">
</td></table>


Output

FoodItem Portion size
hamburgerPotatosaladBrocolliApple 2365


Expected Output

FoodItem Portion Size
hamburger 2
potato salad 3
Brocolli 6
Apple 5

Answer

You need to add a new tr when adding data to your table. This can be done like this:

$(document).ready(function() {
  var food = ['hamburger', 'Potato salad', 'Brocolli', 'Apple pie'];
  var portion = [2, 3, 6, 5];
  for (i = 0; i < food.length; i++) {
    $('#myTable > tbody:last-child').append('<tr><td>' + food[i] + '</td><td>' + portion[i] + '</td></tr>');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
  <thead>
    <tr>
      <th>Food Item</th>
      <th>Portion Size</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>