简体   繁体   English

添加文本框值并使用javascript显示它

[英]adding the text box values and display it using javascript

I'm trying to add the input values of several text boxes using javascript and display the total number below. 我正在尝试使用javascript添加多个文本框的输入值,并在下面显示总数。 How can I add and keep the sum for displaying after the computation. 如何在计算后添加和保留要显示的总和。 I'm not an expert in javascript. 我不是javascript方面的专家。

Here is an example that shows you how to do this: 这是一个示例,向您展示如何执行此操作:

<form name="myFormName">
    <p><input type="text" name="myInputName1" value="25.3"></p>
    <p><input type="text" name="myInputName2" value="14.2"></p>
</form>
<div id="total"></div>

<script type="text/javascript>

    var total = parseFloat(0, 10);

    total += parseFloat(document.myFormName.myInputName1.value, 10);
    total += parseFloat(document.myFormName.myInputName2.value, 10);

    document.getElementById("total").innerHTML = "Total is " + total;

</script>

Well, let's say you have 5 textboxes, with the id text1, text2, text3, text4 and text5: 好吧,假设您有5个文本框,其ID为text1,text2,text3,text4和text5:

var boxes = ['text1', 'text2', 'text3', 'text4', 'text5'],
    sum = 0,
    i = 0,
    len = boxes.length;

for(; i < len; ++i){
    sum += parseInt(document.getElementById(boxes[i]).value, 10); // Use parseFloat if you're dealing with floating point numbers.
}
alert(sum);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM