使用Javascript根据多个输入计算值

时间:2012-06-25 23:04:15

标签: javascript html

我有一个名为price的输入文本框,我插入一个Number值。我将输入设置如下:

<input  name="pound[]" id="pound"/>
<input  name="pound[]" id="pound"/>
<input  name="pound[]" id="pound"/>

如何使用javascript获取值的总和并使用下面的代码显示?

<input  name="total" id="total"/>

1 个答案:

答案 0 :(得分:0)

HTML:

<input  name="pound[]" value="1" id="pound1" class="pound"/>
<input  name="pound[]" value="1" id="pound2" class="pound"/>
<input  name="pound[]" value="1" id="pound3" class="pound"/>
<input  name="total" id="total"/>

<button id="claculate">claculate</button>

JS:

window.onload = function(){
    var btn = document.getElementById('claculate');
    var total = 0;

    btn.onclick = function(){
        var pounds = document.getElementsByClassName('pound');
        for(var i=0;i<pounds.length;i++){
          total = total + parseFloat(pounds[i].value);
        }
        var tot_id = document.getElementById('total');
        tot_id.value = total;
    }
}

演示http://jsfiddle.net/6kFAM/2/