Joao Victor Souza
Joao Victor Souza

Reputation: 293

jQuery repeat action based on input value

I have two inputs: #price and #installments

After inserting both values, I need to append the information in a table. So lets say the #price is '500' and #installments is '5'. The table would be like so:

(installmentNumber) / (installmentPrice)
#1                  /        100
#2                  /        100
#3                  /        100
#4                  /        100
#5                  /        100

I have the following code

$(document).on('blur', "#installments", function(e){
       e.preventDefault();
       var numberOfInstallments = $('#installments').val();
       var installmentPrice = ($('#price').val() / $('#installments').val());
       var installmentNumber = 1;
       $('#tbody').html('');
       $('#tbody').append(new Array(++numberOfInstallments).join('<tr><td>' + installmentNumber++ + '</td><td>' + installmentPrice + '</td></tr>'));
});

but installmentNumber++ doesn't work, it gives me the same value in every row, which is '1'. I guess I need a different approach to this.

Any help would be great

Upvotes: 0

Views: 36

Answers (1)

Tyler Roper
Tyler Roper

Reputation: 21672

You're very close, but I believe the crucial element that you're missing is some sort of loop. You need the append to happen numberOfInstallments times over.

You can accomplish this with a simple for loop:

$(document).on('blur', "#installments", function(e) {
  e.preventDefault();
  var numberOfInstallments = +$('#installments').val();
  var installmentPrice = ($('#price').val() / $('#installments').val());
  
  $("#tbody tr").remove(); //Remove all rows
  
  for (var i = 1; i <= numberOfInstallments; i++)   //Repeat {numberOfInstallments} times
    $('#tbody').append('<tr><td>' + i + '</td><td>' + installmentPrice + '</td></tr>');
});
input { display: block; }
table { margin-top: 20px; border-collapse: collapse; }
td, th { padding: 5px; border: 1px solid #ccc; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  Price: <input type="text" id="price" />
  Installments: <input type="text" id="installments" />
</div>

<table>
  <thead>
    <tr>
      <th>Installment Number</th>
      <th>Installment Price</th>
    </tr>
  </thead>
  <tbody id="tbody"></tbody>
</table>

Upvotes: 1

Related Questions