jose
jose

Reputation: 303

JS add rows to table. Rows appear and then disappear

I want to add a number of rows to a HTML table, and 9 cells to each row using a JS loop. The problem is that I see in the HTML doc for a short instant (miliseconds) what I want, but later it is erased. Why could it be? This is the code with the JS loop and the HTML.

function calcular() {
  var cantidad = Number(document.getElementById("cantidad").value);
  var numAnos = Number(document.getElementById("numAnos").value);
  var numMeses = Number(document.getElementById("numMeses").value);
  var fecha = document.getElementById("fecha");


  //Meses
  var numFilas = numAnos * 12 + numMeses;

  var table = document.getElementById("tablaDatos");
  alert(Number(numFilas));
  for (var i = 0; i < Number(numFilas); i++) {
    alert(table.rows.length);
    var newTR = table.insertRow(table.rows.length);
    //var row = table1.insertRow(table1.rows.length);

    //num  cuota
    var newTD0 = newTR.insertCell(0);
    newTD0.innerHTML = i;
    var newTD1 = newTR.insertCell(1);
    var newTD2 = newTR.insertCell(2);
    var newTD3 = newTR.insertCell(3);
    var newTD4 = newTR.insertCell(4);
    var newTD5 = newTR.insertCell(5);
    var newTD6 = newTR.insertCell(6);
    var newTD7 = newTR.insertCell(7);
    var newTD8 = newTR.insertCell(8);

  }
}
<form action="" name="formDatosInicio">
  Cantidad: <input type="text" id="cantidad" name="cantidad"><br> Num años: <input type="text" id="numAnos" name="numAnos"><br> Num meses: <input type="text" id="numMeses" name="numMeses"><br> Fecha:
  <input type="date" id="fecha" name="fecha"><br>
  <input type="submit" value="Calcular" onclick="calcular()">
</form>


<table id="tablaDatos" name="tablaDatos" style="width:100%" style="text-align:center" align="center" border="1">
  <tr>
    <td>Numero cuota</td>
    <td>Fecha emision</td>
    <td>Saldo pendiente</td>
    <td>Importe cuota</td>
    <td>Amortizacion</td>
    <td>Suma Amortizacion</td>
    <td>Interes</td>
    <td>Suma Interes</td>
    <td>% Interes</td>
  </tr>

</table>

Upvotes: 0

Views: 979

Answers (1)

Steven Johnston
Steven Johnston

Reputation: 1849

Your button is submitting the form and is refreshing the page. Change your button from type submit to type button.

<input type="button" value="Calcular" onclick="calcular()">

Upvotes: 2

Related Questions