How to save columns of an HTML table in an array?

0

I have a little problem with a project that I'm working on. It turns out that I need to capture the data from an html table that the user creates dynamically and when I click on "Save data" I need to save them in an array This is my table:

I know how to capture the values of each cell, but I can not save it in the array, I'm sure I'm doing something wrong, try this:

var i
for (i=1;i<=cantfilas;i++) {
 codigoarray[i] = document.getElementById('tabla').tBodies[0].rows[1].cells[0].innerHTML;}

I appreciate the help in advance

    
asked by Diego Arce 11.10.2018 в 14:51
source

2 answers

1

It is best to assign a class name to each column of the table, and extract the values by iterating the rows of the table to assign the values to the array. Something like this:

let materiales = [];

document.querySelectorAll('.tabla-materiales tbody tr').forEach(function(e){
  let fila = {
    codigo: e.querySelector('.codigo').innerText,
    material: e.querySelector('.material').innerText,
    cantidad: e.querySelector('.cantidad').innerText,
    magnitud: e.querySelector('.magnitud').innerText
  };
  materiales.push(fila);
});

console.log(materiales);
<table class="tabla-materiales">
  <thead>
    <th>Codigo</th>
    <th>Material</th>
    <th>Cantidad</th>
    <th>Magnitud</th>
  </thead>
  <tbody>
    <tr>
      <td class="codigo">1</td>
      <td class="material">Ladrillo Común</td>
      <td class="cantidad">50</td>
      <td class="magnitud">un</td>
    </tr>
    <tr>
      <td class="codigo">2</td>
      <td class="material">Arena Lavada</td>
      <td class="cantidad">2</td>
      <td class="magnitud">m3</td>
    </tr>
    <tr>
      <td class="codigo">3</td>
      <td class="material">Murokal de 5 Lts</td>
      <td class="cantidad">1</td>
      <td class="magnitud">un</td>
    </tr>
  </tbody>
</table>
    
answered by 11.10.2018 / 17:43
source
1

I do not understand well if you have problems in looking for the number of items in the table or saving the data by column. If the case is for the columns you could create a JavaScript object " {columna0:0, columna1:0} " and save this object in the array

codigoarray.push({columna0:0,columna1:0}) .

In any case I see that you have some input you can do this from the action of the "Ok" button that you show in the image or you could use a very good Jquery plugin that I used to manipulate tables.

DataTables

    
answered by 11.10.2018 в 15:21