Create plot table dynamically with jquery?

Asked

Viewed 1,553 times

1

I have a select with amount of plots, and would like to add the rows in the table dynamically with the amount of plots 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>
<button id="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 a couple of hours and I’ve made so many adjustments I can’t think of a solution.

2 answers

2


You have to increase the x otherwise you’re 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>
<button id="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>

  • I made a primary mistake, thank you for your help.

  • @Wagnerfernandomo anything, I’m glad I helped.

1

You can use the DOM to include the lines, I think it’s easier and it’s dynamic too. Follow 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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.