Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

262
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda