jQuery calculate sum of values in all text fields

前端 未结 9 1231
渐次进展
渐次进展 2020-11-29 19:52

I have an order form with about 30 text fields that contain numerical values. I\'d like to calculate the sum of all those values on blur.

I know how to select all te

相关标签:
9条回答
  • 2020-11-29 20:06

    This should fix it:

    var total = 0;   
    $(".price").each( function(){
              total += $(this).val() * 1;
    });
    
    0 讨论(0)
  • 2020-11-29 20:08
    $(".price").each(function(){ 
    total_price += parseFloat($(this).val()); 
    }); 
    

    please try like this...

    0 讨论(0)
  • 2020-11-29 20:11

    If you don't need to support IE8 then you can use the native Javascript Array.prototype.reduce() method. You will need to convert your JQuery object into an array first:

     var sum = $('.price').toArray().reduce(function(sum,element) {
         if(isNaN(sum)) sum = 0;
         return sum + Number(element.value);
     }, 0);
    

    Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

    0 讨论(0)
  • 2020-11-29 20:11

    Similarly along the lines of these answers written as a plugin:

    $.fn.sum = function () {
        var sum = 0;
        this.each(function () {
            sum += 1*($(this).val());
        });
        return sum;
    };
    

    For the record 1 * x is faster than Number(x) in Chrome

    0 讨论(0)
  • 2020-11-29 20:11

    This will work 100%:

    <script type="text/javascript">
    
    function calculate(){
    var result = document.getElementById('result');
    var el, i = 0, total = 0; 
    while(el = document.getElementById('v'+(i++)) ) {
    el.value = el.value.replace(/\\D/,"");
    total = total + Number(el.value);
    }
    result.value = total;
    if(document.getElementById('v0').value =="" && document.getElementById('v1').value =="" && document.getElementById('v2').value =="" ){
     result.value ="";
    }
    }
    </script>
    Some number:<input type="text" id ="v0" onkeyup="calculate()"><br>
    Some number:<input type="text" id ="v1" onkeyup="calculate()"><br>
    Some number:<input type="text" id ="v2" onkeyup="calculate()"><br>
    Result: <input type="text" id="result" onkeyup="calculate()"  readonly><br>
    
    0 讨论(0)
  • 2020-11-29 20:14

    $('.price').blur(function () {
        var sum = 0;
        $('.price').each(function() {
            sum += Number($(this).val());
        });
    
        // here, you have your sum
    });​​​​​​​​​
    
    0 讨论(0)
提交回复
热议问题