How to deduct value continuously on a for loop

I have an input field encased in a for each loop which causes to replicate them into 8 input fields, now I am using for loop to put values in the said input fields and I’m trying to figure out how to deduct the extra payment row by row (example: I have given the input field a value of 3000 which is replicated x8, if I set a payment of 4000 the dbalance will be 0 then I will deduct the extra 1000 to the mbalance, same with the instance if I set a higher payment, deduct the extra value to the next row… here’s my current code:

<tr>
    <td>Down Payment</td>
    <td><input type="text" class="damount" name="damount" id="damount" style="border: none" value="{{ $down_payment }}"></td>
    <td><input type="text" class="dbalance" name="dbalance" id="dbalance" style="border: none" value="0"></td>
</tr>
@foreach($dates as $d)
<tr>
    <td>{{ $d['dates'] }}</td>
    <td><input type="text" class="dmonthly" name="dmonthly[]" id="dmonthly" style="border: none" value="{{ $monthly }}"></td>
    <td><input type="text" class="mbalance" name="mbalance[]" id="dbalance" style="border: none" value="0"></td>
</tr>
@endforeach

<tr>
    <td>
        <div>Need to pay:</div>
        <input type="text" name="down" id="down" value="{{ $down_payment }}" readonly>
        </div>
    </td>
</tr>
<tr>
    <td>
        <div>Payment:</div>
        <div><input type="text" name="pay" id="pay" /></div>
    </td>
</tr>

function calculate() {
  var due = {{ $due }};
  var monthly = {{ $monthly }};
  var down = parseFloat($('#down').val());
  var payment = parseFloat($('#payment').val());
  var total = (down - payment);
  var deducted = (monthly - total);

  if(total > 0) {
    document.querySelector("#dbalance").value = parseFloat(total.toFixed(2));
    const collection = document.getElementsByClassName("mbalance");
    for (let i = 0; i < collection.length; i++) {
        collection[i].value = parseFloat(monthly.toFixed(2));
    }
  } else {
    document.querySelector("#dbalance").value = 0;
    const collection = document.getElementsByClassName("mbalance");
    for (let i = 0; i < collection.length; i++) {
        collection[i].value = parseFloat(deducted.toFixed(2));
    }
  }
}