I've made a simple table in HTML, CSS and Bootstrap, and I want to change the dates that are in the cells. (translate text)
<table class="table table-striped" id="TabelPret">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">service</th>
<th scope="col">price(Euro)</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>consulting</td>
<td>50</td>
</tr>
<tr>
<th scope="row">2</th>
<td>RECONSULT</td>
<td>15</td>
</tr>
<tr>
<th scope="row">3</th>
<td>1 procedur/30 min</td>
<td>10</td>
</tr>
</tbody>
</table>
Now for JS, i try to select the table then to add new rows and colums:
var array = [
["a1", "b1", "c1"],
["a2", "b1", "c1"],
["a3", "b1", "c1"],
["a4", "b1", "c1"],
["a5", "b1", "c1"],
["a6", "b1", "c1"],
["a7", "b1", "c1"]
];
That array will be the new cells so (a1
is translate for id, b1
is translate for consulting, c1
is translate for price...etc)
table = document.getElementById("TabelPret");
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; i < table.rows[i].cells.length; j++) {
table.rows[i].innerHTML = array[i][j];
}
}
This code doesn't work for me, is there another option ? Only in pure JavaScript, the table will be static.
Thanks for your help and time.
Loop over the array instead and use document.createElement
to create rows and cells to append to the tbody
.
const tbody = document.querySelector('table > tbody');
var array = [
["a1", "b1", "c1"],
["a2", "b1", "c1"],
["a3", "b1", "c1"],
["a4", "b1", "c1"],
["a5", "b1", "c1"],
["a6", "b1", "c1"],
["a7", "b1", "c1"],
];
for (var i = 0; i < array.length; i++) {
const row = document.createElement('tr');
for (var j = 0; j < array[i].length; j++) {
const cell = document.createElement('td');
cell.textContent = array[i][j];
row.appendChild(cell);
}
tbody.appendChild(row);
}
<link href="https://getbootstrap.com/docs/4.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<table class="table table-striped" id="TabelPret">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">service</th>
<th scope="col">price(Euro)</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Try this in your loop to reference each cell and assign from your 2d array:
table.rows[i].cells[j].innerHTML = array[i][j];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With