【问题标题】:How to calculate sum of multiple dynamic input fields in Javascript?如何计算Javascript中多个动态输入字段的总和?
【发布时间】:2019-11-10 02:42:57
【问题描述】:

我正在尝试通过 javascript 计算多个动态输入字段的总和。

这是我的主要输入:

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

这就是我添加输入的方式:

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

e.preventDefault();

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

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

在此之后,我有一个自定义函数,可以根据输入计算数据:

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

它只计算一个输入(不是添加的输入)。现在,我想计算使用上述函数创建后显示的每个输入值的价格总和。

预期结果:

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

因此,小计变量应填充每个输入的总和。 谢谢。

更新

现在,我如何计算每行的总和以及小计。在函数下方,您可以找到预期的结果图片链接。

我的完整javascript函数:

$(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;
        });

我的全动态插入输入:

$('.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);

        });

这里是现在的链接和预期的结果: https://ibb.co/sVv3qGF

【问题讨论】:

    标签: javascript jquery arrays dynamic


    【解决方案1】:

    您为多个元素提供了相同的 id。改为上课。然后得到他们的总和。

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

    【讨论】:

      【解决方案2】:

      试试这样。在HTML 元素中使用class,在jquery 中尝试循环获取值并求和。

      $('.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.com/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"/>

      【讨论】:

      • 感谢您的帮助,它正在使用单击事件按钮,但我正在尝试使用 keydown keyup change 事件,它不起作用,它只显示第一个输入值。你能帮我解决这个问题吗?
      • 我已经更新了其他问题,您能帮我解决这个问题吗?
      【解决方案3】:

      首先,您添加输入的模板字符串是错误的,ID 顾名思义是唯一标识符,并且只能在页面上使用一次。你不需要 id 所以从模板中删除它

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

      现在只需更新输入求和函数:

      function sum() {
          var priceElements = document.querySelectorAll('[name^=price]');
          var sum = 0;
          priceElements.forEach(function(element) {
             sum = sum + element.value;
          });
          console.log(sum);   
      }
      

      【讨论】:

        【解决方案4】:
        • 在添加动态输入字段的时候,你应该给唯一的id 每个字段。
        • 然后维护唯一 ID 列表。
        • 迭代该列表并计算总和。

        【讨论】:

          【解决方案5】:
          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);
          })
          

          【讨论】:

          【解决方案6】:

          给每个输入一个公共类。给,下面给代码试试。

          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="">

          【讨论】:

            猜你喜欢
            • 2013-06-02
            • 1970-01-01
            • 2023-03-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-01-04
            相关资源
            最近更新 更多