Javascript - Dynamically populate second column of table html

Asked

Viewed 529 times

0

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

  • Zaira, could post the table code?

  • Post the code you have so far.

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 lines, access the second cell of the line 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>

  • Thanks for the suggestion.. It worked very well, I was able to fill the table as intended

Browser other questions tagged

You are not signed in. Login or sign up in order to post.