I am trying to insert a column of cells with data from an array. I have tried using a for loop, but that just put all the data of the array in each new cell. My goal is to have the new cells display row_header1, row_header2, or row_header3 respectively.
Can anyone help me with this issue? Thank you.
-for loop I’vs tried.
JavaScript
x
3
1
for (var i = 0, len = arr1.length; i < len; i++) {
2
$("tr").find("td:first").before('<td>' + arr1[i] + '</td>')
3
JavaScript
1
12
12
1
var arr1 = ["row_header1", "row_header2", "row_header3"];
2
3
$(document).ready(function() {
4
$("#btn").click(function() {
5
var i = 0,
6
len = arr1.length;
7
i < len;
8
i++;
9
10
$("tr").find("td:first").before('<td>' + arr1[i] + '</td>')
11
});
12
});
JavaScript
1
11
11
1
td,
2
th {
3
padding: 4px;
4
border: solid;
5
width: 50px;
6
height: 50px;
7
}
8
9
table {
10
border-collapse: collapse;
11
}
JavaScript
1
28
28
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<button id="btn">+</button>
3
<table id='table'>
4
<tr>
5
<td>
6
</td>
7
<td>
8
</td>
9
<td>
10
</td>
11
</tr>
12
<tr>
13
<td>
14
</td>
15
<td>
16
</td>
17
<td>
18
</td>
19
</tr>
20
<tr>
21
<td>
22
</td>
23
<td>
24
</td>
25
<td>
26
</td>
27
</tr>
28
</table>
Advertisement
Answer
I think you need to select the right tr
each time when you want to assign value
JavaScript
1
12
12
1
var arr1 = ["row_header1", "row_header2", "row_header3"];
2
3
$(document).ready(function() {
4
$("#btn").click(function() {
5
var i = 0,
6
len = arr1.length;
7
while(i< len){
8
$("tr:eq("+i+")").find("td:first").before('<td>' + arr1[i] + '</td>');
9
i++;
10
}
11
});
12
});
JavaScript
1
11
11
1
td,
2
th {
3
padding: 4px;
4
border: solid;
5
width: 50px;
6
height: 50px;
7
}
8
9
table {
10
border-collapse: collapse;
11
}
JavaScript
1
28
28
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<button id="btn">+</button>
3
<table id='table'>
4
<tr>
5
<td>
6
</td>
7
<td>
8
</td>
9
<td>
10
</td>
11
</tr>
12
<tr>
13
<td>
14
</td>
15
<td>
16
</td>
17
<td>
18
</td>
19
</tr>
20
<tr>
21
<td>
22
</td>
23
<td>
24
</td>
25
<td>
26
</td>
27
</tr>
28
</table>