最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to calculate sum of multiple dynamic input fields in Javascript? - Stack Overflow

programmeradmin5浏览0评论

I'm trying to calculate sum of multiple dynamic input fields via javascript.

This is my main input:

<input type="text" name="price[]" id="price" value="" class="form-control" />

This is how I'm adding inputs:

$('.btn-add-srvice').on('click', function(e){

e.preventDefault();

var template = '<input type="text" name="price[]" id="price" class="form-control" />';

$(this).before(template);
});

After this, I have a custom function which calculate data from inputs:

function sum() {
    var price = document.getElementById('price').value;    
    var subtotal;    
}

It is calculating only one input(not the added inputs). Now, I want to calculate sum of the price of each inputs value that are showing after creating with above function.

Expected result:

input1 = 30
input2 = 30
...... = ...
subtotal = ...

So, the subtotal variable should be filled with sum of for each inputs. Thank you.

Updated

Now, how could I calculate sum of each row and also subtotal. Below the functions you can find the expected result image link.

My full javascript function:

$(document).on('keyup keydown change', ".price, .months, #mwst, #rabatt",function () {
            var months = document.getElementById('months').value;
            var mwst = document.getElementById('mwst').value;
            var rabatt = document.getElementById('rabatt').value;
           
             var priceSum = 0;
             var monthsSum = 0;
                $('.price').each(function(){
                    priceSum += parseFloat(this.value);
                });
                $('.months').each(function(){
                    monthsSum += parseFloat(this.value);
                });
                var subtotal = priceSum * monthsSum;
                var sum = priceSum * months;
                var mwstValue = subtotal + 7.7 / 100 * subtotal - subtotal;
                document.getElementById('subtotal').value = subtotal.toFixed(2);
                document.getElementById('sum').value = subtotal.toFixed(2);
                document.getElementById('mwst').value = mwstValue.toFixed(2);
                var percentage = (mwst / 100) * subtotal;
                var result = subtotal + mwstValue - parseFloat(rabatt);
                document.getElementById('total').value = result;
        });

My full dynamic inserted inputs:

$('.btn-add-srvice').on('click', function(e){

            e.preventDefault();

            var template = 
            '<div class="col-md-12" style="padding:0">'+
                '<div class="col-md-6" style="padding-left:0px">'+
                    '<div class="form-group">'+
                         '<select style="width: 100%" id="service_id" name="service_id[]" class="service_id ">'+
                         '@foreach($servicesList as $sli)'+                                 
                         '<option value="{{$sli->id}}">{{$sli->name}}</option>'+
                          '@endforeach'+
                          '</select>'+
                    '</div>'+
                '</div>'+
                '<div class="col-md-3" style="padding-right:0px">'+
                    '<div class="form-group">'+
                        '<input type="text" name="price[]" id="price" value="" class="form-control price" />'+                      
                    '</div>'+
                '</div>'+
                '<div class="col-md-1" style="padding-right:0px">'+
                    '<div class="form-group">'+
                        '<input type="text" name="months[]" id="months" value="" class="form-control months" />'+                       
                    '</div>'+
                '</div>'+
                '<div class="col-md-2" style="padding-right:0px">'+
                    '<div class="form-group">'+
                        '<input type="text" name="sum[]" id="sum" value="" class="form-control sum" />'+                        
                    '</div>'+
                '</div>'+
                '<div>'+
                /*'<button type="button" class="btn btn-default btn-xs remove">Remove</button>'+*/
                '</div>'+
            '</div>';
    enter code here
            $(this).before(template);

        });

Here is the link how is looking now and the expected result:

I'm trying to calculate sum of multiple dynamic input fields via javascript.

This is my main input:

<input type="text" name="price[]" id="price" value="" class="form-control" />

This is how I'm adding inputs:

$('.btn-add-srvice').on('click', function(e){

e.preventDefault();

var template = '<input type="text" name="price[]" id="price" class="form-control" />';

$(this).before(template);
});

After this, I have a custom function which calculate data from inputs:

function sum() {
    var price = document.getElementById('price').value;    
    var subtotal;    
}

It is calculating only one input(not the added inputs). Now, I want to calculate sum of the price of each inputs value that are showing after creating with above function.

Expected result:

input1 = 30
input2 = 30
...... = ...
subtotal = ...

So, the subtotal variable should be filled with sum of for each inputs. Thank you.

Updated

Now, how could I calculate sum of each row and also subtotal. Below the functions you can find the expected result image link.

My full javascript function:

$(document).on('keyup keydown change', ".price, .months, #mwst, #rabatt",function () {
            var months = document.getElementById('months').value;
            var mwst = document.getElementById('mwst').value;
            var rabatt = document.getElementById('rabatt').value;
           
             var priceSum = 0;
             var monthsSum = 0;
                $('.price').each(function(){
                    priceSum += parseFloat(this.value);
                });
                $('.months').each(function(){
                    monthsSum += parseFloat(this.value);
                });
                var subtotal = priceSum * monthsSum;
                var sum = priceSum * months;
                var mwstValue = subtotal + 7.7 / 100 * subtotal - subtotal;
                document.getElementById('subtotal').value = subtotal.toFixed(2);
                document.getElementById('sum').value = subtotal.toFixed(2);
                document.getElementById('mwst').value = mwstValue.toFixed(2);
                var percentage = (mwst / 100) * subtotal;
                var result = subtotal + mwstValue - parseFloat(rabatt);
                document.getElementById('total').value = result;
        });

My full dynamic inserted inputs:

$('.btn-add-srvice').on('click', function(e){

            e.preventDefault();

            var template = 
            '<div class="col-md-12" style="padding:0">'+
                '<div class="col-md-6" style="padding-left:0px">'+
                    '<div class="form-group">'+
                         '<select style="width: 100%" id="service_id" name="service_id[]" class="service_id ">'+
                         '@foreach($servicesList as $sli)'+                                 
                         '<option value="{{$sli->id}}">{{$sli->name}}</option>'+
                          '@endforeach'+
                          '</select>'+
                    '</div>'+
                '</div>'+
                '<div class="col-md-3" style="padding-right:0px">'+
                    '<div class="form-group">'+
                        '<input type="text" name="price[]" id="price" value="" class="form-control price" />'+                      
                    '</div>'+
                '</div>'+
                '<div class="col-md-1" style="padding-right:0px">'+
                    '<div class="form-group">'+
                        '<input type="text" name="months[]" id="months" value="" class="form-control months" />'+                       
                    '</div>'+
                '</div>'+
                '<div class="col-md-2" style="padding-right:0px">'+
                    '<div class="form-group">'+
                        '<input type="text" name="sum[]" id="sum" value="" class="form-control sum" />'+                        
                    '</div>'+
                '</div>'+
                '<div>'+
                /*'<button type="button" class="btn btn-default btn-xs remove">Remove</button>'+*/
                '</div>'+
            '</div>';
    enter code here
            $(this).before(template);

        });

Here is the link how is looking now and the expected result: https://ibb.co/sVv3qGF

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jun 28, 2019 at 6:19 Besart HaziriBesart Haziri 671 silver badge7 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 2

You are giving same id to multiple elements. Give class instead. Then get their sum.

var sum = 0;
$('.price').each(function(){
    sum += parseFloat(this.value);
});

Try like this. use class in HTML elements and in jquery try to loop and get the value and sum it.

$('.btn-add-srvice').on('click', function(e){

  e.preventDefault();

  var template = '<input type="text" name="price[]" id="price" class="form-control price" />';

  $(this).before(template);
});
$(document).on('keyup', ".price",function () {
  var total = 0;
  
  $('.price').each(function(){
    total += parseFloat($(this).val());
  })  

  console.log(total)
})
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" name="price[]" id="price" value="" class="form-control price" />

<input type ="button" value="add" class="btn-add-srvice"/>

First, your template string for adding inputs is wrong, an ID is, as the name implies, a unique identifier and can only be used once on a page. You don't need id so remove it from the template

var template = '<input type="text" name="price[]" class="form-control" />':

Now just update the input sum function:

function sum() {
    var priceElements = document.querySelectorAll('[name^=price]');
    var sum = 0;
    priceElements.forEach(function(element) {
       sum = sum + element.value;
    });
    console.log(sum);   
}
  • At the time of adding dynamic input field, you should give unique id for each field.
  • Then Maintain the list of unique ids.
  • Iterate on that list and calculate the sum.
let subtotal;

const summOfValues = (summ, element) => summ + Number(element.value);

$('.btn-add-srvice').on('input', function(){
   subtotal = $('[name="price[]"]',this).toArray().reduce(summOfValues);
   $('other').val(subtotal);
})

Give each input a mon class. Give, the below give code a try.

function doSum() {
  var x_names = document.getElementsByClassName("x_name")

  for(var i = 0; i < x_names.length; i++) {
    alert(x_names[i].value)
    // You can do sum of values here
  }
}
<input type="text" class="some_name" name="price[]" id="price" value="">
<input type="text" class="some_name" name="somethingElse" id="somethingElse" value="">

发布评论

评论列表(0)

  1. 暂无评论