herdofturtles21 herdofturtles21 - 4 months ago 13
Javascript Question

Getting javascript to add amounts into a total box on onkeyup



<% total = 0 %>
<% line = 1 %>
<% FOREACH r IN records %>
<% total = total + r.AmountOwed %>

<div class="w-row lineitems">
<div class="w-col w-col-4">
<div><% r.ServiceDate %></div>
</div>
<div class="w-col w-col-4">
<div>$<% r.AmountOwed %></div>
</div>

<div class="w-col w-col-4 column-left">
<input id='Line Item <% line %>' type="text" onkeyup="updateTotal()" placeholder="Amount" name="AmountPaying" class="field m w-input" value="<% r.AmountOwed %>" >

</div>

</div>
<% line = line + 1 %>
<% END %>
<input id="numberoflines" type="hidden" name="numberoflines" value='<% line %>'>
<div class="lineitems w-row">
<div class="w-col w-col-4">
<div>
<div class="footerblock">Total</div>
</div>
</div>
<div class="w-col w-col-4">
<div>
<div class="footerblock"> $<% total %></div>
</div>
</div>





I have a form that uses a loop to populate line items with their amount owed. There can be any amount of lines items based on whats in the database. Beside each line item is an input box that you enter the amount you want to pay in.
At the end of the line items there is an input box that should be updated using onkeyup that adds all the amount paying to display the total amount that has been entered. Here is the javascript I'm using to do this but it only updates the total box with whats in the last line item. numberoflines has the total number of line items there are.



function updateTotal() {
for (i = 1; i < document.getElementById("numberoflines").value; i++ ) {
document.getElementById("totalpaying").value = (+document.getElementById(("Line Item " + i)).value);
}




Answer

Because you keep replacing the value instead of adding to it. You need to use += instead of just =

I also utilize the Number() Javascript function as it will return NaN if there is not a number in the input. Bearing in mind you should check for that on your own as well. What is the difference between parseInt(string) and Number(string) in JavaScript?

Try changing it to:

function updateTotal() {
    var total = 0;
    for (i = 1; i < document.getElementById("numberoflines").value; i++ ) {
      total += Number(document.getElementById(("Line Item " + i)).value);
    }
    document.getElementById("totalpaying").value = total;
}