GXM100
GXM100

Reputation: 467

Adding Within Each Loop Jquery

I have the below

$('.amount2').on("input", function() {
  var total = 0;
  var i = 0;
  $('#manifest-table25 .amount2').each(function() {

    total += $('#id_form-'+(i)+'-Amount').val();
    i++;
  })
  
  $('#id_InvoiceTotal').val(total);
});

What is confusing me is that when I enter the value 5 into the input I would expect for the total to equal 5, instead it shows on the UI as 05. How do I remove the leading zero/any thoughts on what is causing it? It is an integerfield in the model not charfield.

Upvotes: 0

Views: 25

Answers (1)

Obzi
Obzi

Reputation: 2390

$.val() return a string.
You need to parse it into an integer or a float before doing some math:

$('.amount2').on("input", function() {
  var total = 0;
  var i = 0;
  $('#manifest-table25 .amount2').each(function() {
    total += parseInt($('#id_form-'+(i)+'-Amount').val());
    i++;
  })
  
  $('#id_InvoiceTotal').val(total);
});

Upvotes: 2

Related Questions