Create plots table dynamically with jquery?

1

I have a select with lots of parcels, and would like to add the rows in the table dynamically with the amount of parcels selected. example:

$('#simular').click(function(){
        $('#table').show();
        var parcelas = 4; //simulando 4 parcelas
        var total = 4750.00; //simulando este valor
        var table;
        var x = 1;
        while(x <= parcelas){
            table += '<tr><td> de </td>';
            table += '<td>data</td>';
            table += '<td>$valor</td></tr>';    
            //$('#table tbody').prepend(table); comentei o código pois está dando timeout
        }        
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="simular">Simular</button>
<table id="table" style="display:none;">
  <tr>
    <th>parcela</th>
    <th>valor</th>
  </tr>
  <tbody>
  </tbody>
</table>

I've been standing here for about 2 hours and have made so many adjustments that I can not think of a solution.

    
asked by anonymous 12.09.2017 / 17:15

2 answers

2

You have to increment the x otherwise you stay in an infinite loop ...

$('#simular').click(function() {
  $('#table').show();
  var parcelas = 4; //simulando 4 parcelas
  var total = 4750.00; //simulando este valor
  var table = '';
  var x = 1;
  while (x <= parcelas) {
    table += '<tr><td>' + x + '</td>';
    table += '<td>data</td>';
    table += '<td>$valor</td></tr>';
    x++;
  }
  $('#table tbody').html(table);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="simular">Simular</button>
<table id="table" style="display:none;">
  <thead>
    <tr>
      <th>parcela</th>
      <th>data</th>
      <th>valor</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
    
12.09.2017 / 17:17
1

You can use the DOM to include the rows, I think it's easier and it's dynamic too. Here is an example:

    var table = document.getElementById("tbResumo");
    var row = table.tBodies[0].insertRow();

    var colCodigo = row.insertCell(0);
    var colDescricao = row.insertCell(1);
    var colLote = row.insertCell(2);
    var colQuantidade = row.insertCell(3);

    colCodigo.innerHTML = element.CodProduto;
    colDescricao.innerHTML = element.NomeProduto;
    colLote.innerHTML = element.Lote;
    colQuantidade.innerHTML = element.Quantidade;
    
12.09.2017 / 17:17