Samij
Samij

Reputation: 81

Populate table by looping through array

I got a table where first td of each tr, starting with 2nd tr, has to be populated from an array with items inserted in the order they are in the array.

Here is an example of my JavaScript:

terms = [
     "term 1",
     "term 2",
     "term 3",
     "term 4",
]; 
var terms_length = terms.length;
var r = 1;
r++;
for (var t=0; t < terms_length; t++) {
    $("#termstable tr:nth-child(" + r + ") td:nth-child(1)").html(terms[t]);
}

As of right now, it's populating only 2nd tr's td with last item of the array.

Upvotes: 0

Views: 386

Answers (4)

jo_va
jo_va

Reputation: 13964

You have to increment your r variable in the loop, using ++r instead of r. But it is more simple to simply use t + 2 and remove r. See this live demo:

const terms = [
 "term 1",
 "term 2",
 "term 3",
 "term 4",
]; 

for (let t = 0; t < terms.length; t++) {
  $("#termstable tr:nth-child(" + (t + 2) + ") td:nth-child(1)").html(terms[t]);
}
table {
  border-collapse: collapse;
}

td, th {
  border: 1px solid black;
  min-width: 20px;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<table id="termstable">
  <thead>
    <tr><th>term</th><th>#</th></tr>
  </thead>
  <tbody>
    <tr><td></td><td>0</td></tr>
    <tr><td></td><td>1</td></tr>
    <tr><td></td><td>2</td></tr>
    <tr><td></td><td>3</td></tr>
    <tr><td></td><td>4</td></tr>
  </tbody>
</table>

Upvotes: 0

adeneo
adeneo

Reputation: 318182

Would be quite a lot easier if you just use a little more jQuery

var terms = [
   "term 1",
   "term 2",
   "term 3",
   "term 4" 
]; 

$("#termstable tr:nth-child(n+2) td:first-child").html(function(i) {
    return terms[i];
});

Upvotes: 0

powerc9000
powerc9000

Reputation: 2103

You are not incrementing the variable r in the loop. r gets set to 1 incremented to 2 when r++ runs then never changes

So in every loop the jquery would end up being

$("#termstable tr:nth-child(2) td:nth-child(1)").html(terms[t]);

You need to increment r in the loop as well.

terms = [
     "term 1",
     "term 2",
     "term 3",
     "term 4",
]; 
var terms_length = terms.length;
var r = 1;

for (var t=0; t < terms_length; t++) {
    $("#termstable tr:nth-child(" + r + ") td:nth-child(1)").html(terms[t]);
    r++;
}

Upvotes: 1

r4ccoon
r4ccoon

Reputation: 3136

put your r into the loop

terms = [
 "term 1",
 "term 2",
 "term 3",
 "term 4",
]; 

var terms_length = terms.length;
var r = 1;
for (var t=0; t < terms_length; t++) {
    $("#termstable tr:nth-child(" + r + ") td:nth-child(1)").html(terms[t]);
    r++;
}

Upvotes: 1

Related Questions