I tried using this using the approach as how you typically solve any closure issues but apparently this is not working for me. I tried changing it to let, const or even arrow functions but the code always print the last array element.
Can anyone tell me what I am doing wrong here:
var data = [{
"first_name": "John",
"last_name": "Doe",
"phone": "31227-5325"
}, {
"first_name": "Jane",
"last_name": "Campbell",
"phone": "123123-5325"
}];
window.onload = function() {
console.log('loaded....');
data.forEach(function(elem, index) {
let p = index;
document.querySelector('#fname').innerHTML = '<td>' + data[p].first_name + '</td>';
document.querySelector('#lname').innerHTML = '<td>' + data[p].last_name + '</td>';
document.querySelector('#phone').innerHTML = '<td>' + data[p].phone + '</td>';
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-border">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
</tr>
</thead>
<tr class="tr1">
<td id="fname"></td>
<td id="lname"></td>
<td id="phone"></td>
</tr>
</table>
http://jsbin.com/gasegeqila/1/edit?js,output
Thanks