如何使用Javascript从输入框值获得总和? [英] How get total sum from input box values using Javascript?

查看:165
本文介绍了如何使用Javascript从输入框值获得总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Javascript中并不完美。我想显示在名为total的下一个输入框中的qty输入框中输入的值的总和,而不刷新页面。任何人都可以帮我搞清楚..?

I am not perfect in Javascript.. I want to show total sum of values entered in qty input boxes in next input box named total without refreshing page. Can anyone will help me to figure it out..?

这是javascript

Here is javascript

 <script type="text/javascript"> 
 var howmanytoadd = 2;
 var rows;

 function calc() {
     var tot = 0;
     for (var i = 0; i < rows.length; i++) {
         var linetot = 0;
         rows[i].getElementsByTagName('input')[howmanytoadd].value = linetot;
         tot += linetot;
     }
     document.getElementById('total').value = tot
 }
 onload = function () {
     rows = document.getElementById('tab').getElementById('qty1');
     for (var i = 0; i < rows.length; i++) {
         rows.getElementsByTagName('input')[i].onkeyup = calc;
     }
 }
</script>

这是我的html代码:

Here is my html code:

Qty1 : <input type="text" name="qty1" id="qty"/><br>
Qty2 : <input type="text" name="qty2" id="qty"/><br>
Qty3 : <input type="text" name="qty3" id="qty"/><br>
Qty4 : <input type="text" name="qty4" id="qty"/><br>
Qty5 : <input type="text" name="qty5" id="qty"/><br>
Qty6 : <input type="text" name="qty6" id="qty"/><br>
Qty7 : <input type="text" name="qty7" id="qty"/><br>
Qty8 : <input type="text" name="qty8" id="qty"/><br>
<br><br>
Total : <input type="text" name="total" id="total"/>

这里是屏幕截图

here is screen shot

推荐答案

尝试:

Qty1 : <input onblur="findTotal()" type="text" name="qty" id="qty1"/><br>
Qty2 : <input onblur="findTotal()" type="text" name="qty" id="qty2"/><br>
Qty3 : <input onblur="findTotal()" type="text" name="qty" id="qty3"/><br>
Qty4 : <input onblur="findTotal()" type="text" name="qty" id="qty4"/><br>
Qty5 : <input onblur="findTotal()" type="text" name="qty" id="qty5"/><br>
Qty6 : <input onblur="findTotal()" type="text" name="qty" id="qty6"/><br>
Qty7 : <input onblur="findTotal()" type="text" name="qty" id="qty7"/><br>
Qty8 : <input onblur="findTotal()" type="text" name="qty" id="qty8"/><br>
<br><br>
Total : <input type="text" name="total" id="total"/>


    <script type="text/javascript">
function findTotal(){
    var arr = document.getElementsByName('qty');
    var tot=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].value))
            tot += parseInt(arr[i].value);
    }
    document.getElementById('total').value = tot;
}

    </script>

这篇关于如何使用Javascript从输入框值获得总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆