1

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

5
  • 1
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. Commented Oct 18, 2017 at 11:03
  • With that said, your problem is because you're setting the value of each element in the loop, so only the values set in the last iteration are visible. You instead need to create a new row in the loop, and set the values in there Commented Oct 18, 2017 at 11:05
  • There's nothing inherently wrong with your logic, it's your output, it's writing to the same HTML elements and overwriting your previously inserted data. Commented Oct 18, 2017 at 11:10
  • @RoryMcCrossan: i added the relevant code. Commented Oct 18, 2017 at 11:10
  • @Mike Thanks, I added an answer for you Commented Oct 18, 2017 at 11:20

4 Answers 4

1

Your problem is because you're setting the value of the same elements in the loop, so only the values set in the last iteration are visible.

You instead need to create a new row in the loop and set the values in there, like this:

var data = [{
  "first_name": "John",
  "last_name": "Doe",
  "phone": "31227-5325"
}, {
  "first_name": "Jane",
  "last_name": "Campbell",
  "phone": "123123-5325"
}];

window.onload = function() {
  var tbody = document.querySelector('table tbody');
  
  data.forEach(function(elem, index) {
    var tr = document.createElement('tr');
    tr.innerHTML = `<td>${data[index].first_name}</td><td>${data[index].last_name}</td><td>${data[index].phone}</td>`;
    tbody.appendChild(tr);
  })
}
<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>
  <tbody></tbody>
</table>

Sign up to request clarification or add additional context in comments.

Comments

0

Edit:

One way is to create rows and cells separately like that:

var row = table.insertRow(i + 1);

var cl1 = row.insertCell(0);
var cl2 = row.insertCell(1);
var cl3 = row.insertCell(2);

cl1.innerHTML = data[i].first_name;
cl2.innerHTML = data[i].last_name;
cl3.innerHTML = data[i].phone;

Working example: https://jsfiddle.net/dkppcdtz/1/

1 Comment

I dont want to append, I want to insert a new row for each value
0

You can use array#reduce to create your row string and then add the generated string to your table body.

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....');
  var row = data.reduce(function(str, elem, index) {
    let p = index;
    str += '<tr><td>' + data[p].first_name + '</td><td>' + data[p].last_name + '</td><td>' + data[p].phone + '</td></tr>';
    return str;
  }, '');
  document.querySelector('table tbody').innerHTML = row;
}
<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>
  <tbody class="tr1">
  </tbody>

</table>

Comments

0

the code always print the last array element?

From Docs

The id global attribute defines a unique identifier (ID) which must be unique in the whole document.

From your script :

document.querySelector('#fname').innerHTML = ...;
document.querySelector('#lname').innerHTML = ...;
document.querySelector('#phone'). = .....

You always replacing your data with new one.So,there is last element is getting updated.

You can loop like this,

var table = document.querySelector('.table.table-border');

data.forEach(function(elem, index) {

    let p = index;
    let newRowHtml = '<tr><td>' + data[p].first_name + '</td>' +
                    '<td>' + data[p].last_name + '</td>' +
                    '<td>' + data[p].phone + '</td></tr>';


    table.insertAdjacentHTML('afterend', newRowHtml);

})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.