JavaScript keyup和onload来计算字段总数

时间:2015-07-19 20:38:31

标签: javascript jquery onload keyup

我正在使用JavaScript计算两个文本输入。它适用于keyup。即,在键入时,余额会实时计算。但是,我希望总计不仅可以在keyup上计算和显示,还可以在onload上显示,所以当我加载页面时,它已经计算了字段。

这是我目前使用的仅用于密钥的JavaScript代码

#include <array> 
#include <ttmathuint.h> 

typedef unsigned int uint; 
namespace ttmath { 

    uint AddTwoUInt(uint a, uint b, uint carry, uint * result) 
    { 
        uint temp; 

        if( carry == 0 ) { 
            temp = a + b; 

            if( temp < a ) 
                carry = 1; 
        } else  { 
            carry = 1; 
            temp  = a + b + carry; 

            if( temp > a ) // !(temp<=a) 
                carry = 0; 
        } 

        *result = temp; 

        return carry; 
    } 

    template<uint N> 
    uint Add(const uint * t0, const uint * t1, uint * t2, uint c); 

    template<> 
    uint Add<1>(const uint * t0, const uint * t1, uint * t2, uint c)  { 
        uint i; 
        c = AddTwoUInt(*t0, *t1, c, t2); 
        return c; 
    } 

    template<uint N> 
    uint Add(const uint * t0, const uint * t1 , uint * t2, uint c) { 
        c = Add<N-1>(t0, t1, t2, c); 
        c = AddTwoUInt(t0[N-1], t1[N-1], c, t2+N-1); 
        return c; 
    } 

} 
template<int N> 
ttmath::UInt<N> fib(size_t n) 
{ 
 ttmath::UInt<N> a,b,c; 
 a = 1, b = 1; 

 for (size_t i = 3; i <= n; i++) { 
    ttmath::Add<N>(a.table,b.table,c.table,0); 
    a = b; 
    b = c; 
 }            
 return b;                           
} 

int main(int argc,char ** argv) { 
 std::cerr << fib<15>(500) << std::endl;
} 

2 个答案:

答案 0 :(得分:1)

我认为这样的事情会起作用

    <script type="text/javascript">

    $(document).ready(calculate());   
    $(document).on("keyup", calculate());

    function calculate() {
        var sum = 0;
        $(".totalCal").each(function(){
            sum += +$(this).val();
        });
        $("#total").val(sum);

        document.getElementById('grandTotal').innerHTML = sum.toFixed(2);
        });
    }
</script>

答案 1 :(得分:1)

https://jsfiddle.net/L2s5yoth/

HTML:

<input type="text" value="0" class="totalCal"><br />
<input type="text" value="1" class="totalCal"><br />
<input type="text" value="2" class="totalCal"><br />
<input type="text" value="3" class="totalCal"><br />
<div id="total">0</div>

jQuery的:

$(document).ready(calculate);   
$(document).on("keyup", calculate);

function calculate() {
    var sum = 0;
    $(".totalCal").each(function(){
        sum += +$(this).val();
    });
    $("#total").html(sum);
}