Javascript - Populate second column dynamically from html table [closed]

0

Good morning, guys. I am having problems with tables with javascript, I am new and I am not sure what to do. The question is the following: I have a table created in html with two columns, the first has already been filled using html but the second column must be populated dynamically, I tried to do this but the data only appears in the first row of the second column and does not fill all the lines in that column .. Help me

    
asked by anonymous 10.08.2018 / 09:05

1 answer

1

Assuming your table has a TBODY:

<table id="minhaTabela">
    <thead>
        <tr>
            <td>Valor Fixo</td>
            <td>Valor Dinâmico</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Um</td>
            <td></td>
        </tr>
        <tr>
            <td>Dois</td>
            <td></td>
        </tr>
        <tr>
            <td>Três</td>
            <td></td>
        </tr>
    </tbody>
</table>

You could, for each of the TBODY rows, access the second row cell and define the contents of that cell:

// Acessa a tabela:
var minhaTabela = document.getElementById('minhaTabela');

// Acessa o primeiro tbody da tabela:
var tBody = minhaTabela.tBodies[0];

// Acessa cada linha da tabela:
for (i = 0; i < tBody.rows.length; i++) {

    // Define o valor (i+1) da segunda célula (cells[1]) de cada linha (rows[i]) da tabela:
    tBody.rows[i].cells[1].innerHTML = i+1;
}

See working

// Acessa a tabela:
var minhaTabela = document.getElementById('minhaTabela');

// Acessa o primeiro tbody da tabela:
var tBody = minhaTabela.tBodies[0];

// Acessa cada linha da tabela:
for (i = 0; i < tBody.rows.length; i++) {

    // Define o valor (i+1) da segunda célula (cells[1]) de cada linha (rows[i]) da tabela:
    tBody.rows[i].cells[1].innerHTML = i+1;
}
<table id="minhaTabela">
    <thead>
        <tr>
            <td>Valor Fixo</td>
            <td>Valor Dinâmico</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Um</td>
            <td></td>
        </tr>
        <tr>
            <td>Dois</td>
            <td></td>
        </tr>
        <tr>
            <td>Três</td>
            <td></td>
        </tr>
    </tbody>
</table>
    
10.08.2018 / 13:13