innerHTML in a TR of a JavaScript table

3

Hello, I would like to generate a dynamic table in java script (only the tr and the td) so I am using innerHTML.

I make the following code:

objDiv1 = document.getElementById("tabela");

 bloco += "<tr><td>"+ Campo+"</td></tr>";

objDiv1.innerHTML = bloco;

It is generating certain html however it is playing up my table.

IfIgetandgiveaconsole.logandpasteinplacewherethisdivisgoingtowork:

Myhtmlstructurelookslikethis:

<tableclass="table">
    <thead class=" text-primary">
    <th>
        Lote
    </th>
</thead>
<tbody>
<div id="tabela"> 
</div>
</tbody>

</table>

What am I doing wrong?

    
asked by anonymous 09.10.2018 / 01:15

1 answer

2

I created something fast and described each step in the best possible way for you to understand, in my example I used a form ... I did with pure javascript as well as your code, but I advise you to use jquery.

<html>
    <head>

    </head>
<body>

<script>
 function adicionar()
 {

    //Recupera as informações do campo dos formulários
    var codigo = document.getElementById('codigo').value;
    var nome   = document.getElementById('nome').value;

    //Encontra o elemento tabela
    tabela = document.getElementById("tabela");

    //Inclui uma linha no elemento tabela <tr></tr>
    //informei -1 para criar a linha no final da tabela
    var linha   = tabela.insertRow(-1);

    //Adiciona dua coluna na linha criada <td></td> <td></td>
    var coluna1 = linha.insertCell(0);
    var coluna2 = linha.insertCell(1);

    //Inclui o valor do campo do formulário em sua respectiva coluna
    coluna1.innerHTML = codigo;
    coluna2.innerHTML = nome;
 }
</script>

<form>

    <label for="codigo">Código</label>
    <input type="text" id="codigo">

    <label for="codigo">Nome</label>
    <input type="text" id="nome">

    <input type="button" onclick="return adicionar();" value="Cadastrar">
</form>

<table id="tabela" border="1">
    <tr>
        <td>Codigo</td>
        <td>Nome</td>
    </tr>
    <tr>
        <td>1</td>
        <td>Raphael</td>
    </tr>
</table>


</body>

</html>
    
09.10.2018 / 02:28