apz_fed
apz_fed

Reputation: 25

Creating a table with a loop

I'm quite new to Javascript and I'm trying to populate a table through a loop. The code works fine as long as I only try to populate the table, but when I try to add an IF condition in order to separate headers and data, it does not work any more. I would be curious to understand why it does not work and how can I solve the issue.

Below current broken code:

for(i = 0;i < values.length; i ++){
          var table = document.getElementById("myTable");
          tr = document.createElement('tr');

          for (j = 0; j < values[i].length; j++) {
          if (i=0) {
          td = document.createElement('td');
          tr.appendChild(td);
          td.innerHTML = values[i][j];
          }
          } else { 
          td = document.createElement('td');
          tr.appendChild(td);
          td.innerHTML = values[i][j];
          }
}

Here the code that works without headers:

for(i = 0;i < values.length; i ++){
          var table = document.getElementById("myTable");
          tr = document.createElement('tr');
          for (j = 0; j < values[i].length; j++) {
          td = document.createElement('td');
          tr.appendChild(td);
          td.innerHTML = values[i][j];
          }
           table.appendChild(tr);

}

Upvotes: 0

Views: 56

Answers (1)

elreeda
elreeda

Reputation: 4597

you should put double equal i==0 not i=0

if (i==0) {
    td = document.createElement('td');
    tr.appendChild(td);
    td.innerHTML = values[i][j];
}

EDIT

in your second loup you should close the if statement and loop :

for (i = 0; i < values.length; i++) {
  var table = document.getElementById("myTable");
  tr = document.createElement('tr');

  for (j = 0; j < values[i].length; j++) {
    if (i == 0) {
      td = document.createElement('td');
      tr.appendChild(td);
      td.innerHTML = values[i][j];

    } else {
      td = document.createElement('td');
      tr.appendChild(td);
      td.innerHTML = values[i][j];
    }
  }
}

Upvotes: 1

Related Questions