2

I'm trying to add the input values of several text boxes using javascript and display the total number below. How can I add and keep the sum for displaying after the computation. I'm not an expert in javascript.

Josh Crozier
  • 219,308
  • 53
  • 366
  • 287
coder247
  • 2,833
  • 18
  • 48
  • 69

2 Answers2

3

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>
Fenton
  • 224,347
  • 65
  • 373
  • 385
2

Well, let's say you have 5 textboxes, with the id text1, text2, text3, text4 and 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);
Evan Trimboli
  • 29,459
  • 5
  • 43
  • 65