0

Hoping this is my last question but here goes.

I have an HTML script:

<input type="text" name="copy1" id="copy1" size="4" maxlength="10" onchange="calc1(this.value)">
<input type="text" name="copycosts" id="copycosts" size="4" VALUE="">
 <input name="copy2" type="text" id="copy2" size="4" maxlength="10" onchange="calc2(this.value)">

etc.... I want to add them all together so that they sum up in the total box. I have a different function for each one so that they are all getting their costs and that works great. I just can't get the sum to work. I tried javascripting it:

function sum(){
var cc = document.getElementById("copycosts").value;
var cc2 = document.getElementById("copycosts2").value;
var cc3 = document.getElementById("copycosts3").value;
var sc = document.getElementById("searchcosts").value;
var cc4 = document.getElementById("certcosts").value;
var nc = document.getElementById("naracosts").value;
var ac = document.getElementById("apostcosts").value;

var sum = parseFloat(cc + cc2 + cc3 + sc + cc4 + nc + ac);
document.getElementById("sum").value = sum;
}

what am I doing wrong?

Thanks again

4

1 回答 1

0

HTML:

<input type="text" class="numInput" id="copy1" maxlength="10" />
<input type="text" class="numInput" id="copy2" maxlength="10" />
<input type="text" class="numInput" id="search" maxlength="10" />
<input type="text" class="numInput" id="nara" maxlength="10" />
Sum:
<input type="text" class="numOutput" id="sum" readonly="true" />

JavaScript:

var load = function () {
    'use strict';

    var inElems = document.getElementsByClassName('numInput'),
        sum = document.getElementById('sum'),
        i;

    var add = function () {
        var i, result = 0;

        for (i = 0; i < inElems.length; i++) {
            result += +(inElems.item(i).value);
        }

        sum.value = result;
    };

    for (i = 0; i < inElems.length; i++) {
        inElems.item(i).addEventListener('input', add, false);
    }
}

(function () {
    document.addEventListener('load', load, false);
})();

CSS:

.numInput {
    width: 60px;
}

.numOutput {
    width: 90px;
    readonly: true;
}

jsfiddle

注意:此示例使用可能与旧版浏览器不兼容的现代 JavaScript 技术

于 2013-10-04T18:38:52.807 回答