Eaten Taik
Eaten Taik

Reputation: 938

Sum up appended input value with the current total using jquery

I'm trying to re-calculate the total existing value when a user is typing in the new value in the appended input element. My system is able to do the sum up but the calculation is wrong as it will keep on adding in the number even though the input number is updated.

For example the original total is 400. When user is inserting 2 at first, the total will change to 402. But as the user type in and the input value become 23 the new amount become 425 when it's supposed to be 423

HTML

<p id="total">400</p>
<div id="appended"></div>

<a href="#" onClick="AddRow()">Add Row</a>

jQuery

$('#appended').on('input', '.amount', function(){
    var amount = parseFloat($(this).val());
  var total  = parseFloat($('#total').text())
  var new_total = amount+total;
  
  $('#total').text(new_total)
})

Working code can be found here https://jsfiddle.net/foek1846/

Upvotes: 0

Views: 1206

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370659

Save the initial total in a variable first:

const origTotal = Number($('#total').text());

function AddRow() {
  $('#appended').append(`<input class="form-control amount" value="" />`);
}

$('#appended').on('input', '.amount', function() {
  const amountSum = [...$('.amount')]
    .map(input => Number(input.value))
    .reduce((a, b) => a + b, 0);
  $('#total').text(origTotal + amountSum)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="total">400</p>
<div id="appended"></div>

<a href="#" onClick="AddRow()">Add Row</a>

Upvotes: 1

Related Questions