Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate table in pure js

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.

like image 254
andrei0292 Avatar asked Jul 14 '20 19:07

andrei0292


2 Answers

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>
like image 52
Unmitigated Avatar answered Nov 15 '22 20:11

Unmitigated


Try this in your loop to reference each cell and assign from your 2d array:

table.rows[i].cells[j].innerHTML = array[i][j];
like image 2
Eric Svitok Avatar answered Nov 15 '22 19:11

Eric Svitok