gpt4 book ai didi

javascript - 使用 Javascript 从输入框值中获取总和,带小数

转载 作者:行者123 更新时间:2023-11-28 15:14:12 50 4
gpt4 key购买 nike

我从另一个答案复制了这个,它有效,但我需要得到小数点后面的两个数字。本轮...

Qty1 : <input onblur="findTotal()" type="text" name="qty" id="qty2"/><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>

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>

最佳答案

将脚本替换为以下内容:

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

</script>

关于javascript - 使用 Javascript 从输入框值中获取总和,带小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34806041/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com