Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

260
Visualizações
How to use a javascript function to generate a HTML table?

I would like to write a JavaScript function that generates the following HTML Table:

| x | x^2 | 1/x |
|---------------|
| 1 |  1  |  1  |
|---|-----|-----|
| 4 |  16 | 0.25|

And here is my code so far. I have to use a FOR LOOP to construct and tags to place the values of x, x^2, and 1/x into the table. It's incomplete because I'm not really sure what to do from this point. Any help would be appreciated!!

<!DOCTYPE html>

<html>
    <head>
        <style>
        
        table {
            border: 1px solid black;
            width:50%;
            border-collapse:collapse;
            align:center;
        }
        
        th {
            align:center;
            font-weight:bold;
            border: 1px solid black;
        }
        
        </style>
    
        <script>
        
            function square(n)
            {
                var sqNum = n * n;
                return sqNum;
            }
            
            function inverse(n)
            {
                var invNum = 1 / n;
                return invNum;
            }
            
            function generateTable()
            {
                var tableMain = document.getElementById("table");
                
                for (var i = 0; i <= 5; i++)
                {
                    var x = i;
                    var xSquare = square(i);
                    var xInv = inverse(i)
                    
                    
                    
                    
            
        </script>
    </head>
    
    <body>
        <table id="table">
            <tr bgcolor="gainsboro">
                <th>x</th>
                <th>X<sup>2</sup></th>
                <th><sup>1</sup>/<sub>x</sub></th>
            </tr>
        </table>
    </body>
<html>
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Use insertAdjacentHTML and a template literal to create a row.

generateTable();

function generateTable(n = 5) {
  const square = n => n * n;
  const inverse = n => 1 / n;
  const tableMain = document.querySelector("table");

  for (let i = 1; i <= n; i++) {
    tableMain.insertAdjacentHTML(
      `beforeend`,
      `<tr><td>${i}</td><td>${square(i)}</td><td>${inverse(i).toFixed(2)}</td></tr>`)
    }
}
table {
  border: 1px solid black;
  border-collapse: collapse;
  text-align: center;
}

th, td {
  text-align: center;
  font-weight: bold;
  border: 1px solid black;
  padding: 1px 6px;
}

td {
  font-weight: normal;
}
<table id="table">
  <tr bgcolor="gainsboro">
    <th>x</th>
    <th>X<sup>2</sup></th>
    <th><sup>1</sup>/<sub>x</sub></th>
  </tr>
</table>

about 4 years ago · Juan Pablo Isaza Relatório

0

if something is desired maybe so.

function square(n){
    var sqNum = n * n;
    return sqNum;
 }
        
 function inverse(n){
     var invNum = 1 / n;
     return invNum;
 }
        
 function generateTable(){
    var tableMain = document.getElementById("table");
            
    for (var i = 0; i <= 5; i++){
        var x = i;
        var xSquare = square(i);
        var xInv = inverse(i);
        var tr = document.createElement('tr');
        var td1 = document.createElement('td');
        var td2 = document.createElement('td');
        var td3 = document.createElement('td');
        td1.innerHTML = x;
        td2.innerHTML = xSquare;
        td3.innerHTML = xInv;
        tr.appendChild(td1);
        tr.appendChild(td2);
        tr.appendChild(td3);
        tableMain.appendChild(tr);
    }
}
generateTable();
table {
  border: 1px solid black;
  border-collapse: collapse;
  text-align: center;
}

th, td {
  text-align: center;
  font-weight: bold;
  border: 1px solid black;
  padding: 1px 6px;
}

td {
  font-weight: normal;
}
<table id="table">
  <tr bgcolor="gainsboro">
    <th>x</th>
    <th>X<sup>2</sup></th>
    <th><sup>1</sup>/<sub>x</sub></th>
  </tr>
</table>

about 4 years ago · Juan Pablo Isaza Relatório

0

may be like this

-HTML-

<div class="col-sm-6">
  <h3>Example</h3>
  <div class="form-group">
    <input  id="myInput" type="number" value="" />
    <button id="myButton">Add</button>
  </div>

  <div>
   <table id="myTable" class="table table-bordered">
     <thead>
       <tr>
         <th>X</th>
         <th>X^2</th>
         <th>1/X</th>
       </tr>
     </thead>
     <tbody>
     </tbody>
   </table>
  </div>
</div>


-JS-

    function generateRow(rowLimit){
        let myTable = document.getElementById("myTable").getElementsByTagName('tbody')[0];
      myTable.innerHTML = ""; // reset row
        for (let i = 1; i <= rowLimit; i++){
    
        // Insert a row
        let newRow = myTable.insertRow();
    
        // Insert a cell at the new row      
        // firstCell -> value = x
        let cell0 = newRow.insertCell();
        cell0.innerHTML = i;
        
        // secondCell -> square = x * x 
        let cell1 = newRow.insertCell();
        cell1.innerHTML = (i * i);
        
        // lastCell -> inverse = 1 / x
        let cell2 = newRow.insertCell();
        cell2.innerHTML = (1 / i).toFixed(3);
      }
    }
    
    document.getElementById('myButton').addEventListener("click", function(){
        let myInput = document.getElementById("myInput");
      let myValue = myInput.value;    
      generateRow(myValue);
    });

Demo : https://jsfiddle.net/uhLwr8bz/4/

*note: this code using bootstrap.css

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda