Sergi Khizanishvili
Sergi Khizanishvili

Reputation: 587

Sum up the values in the table column

I have following code and I want to sum up the values from the inputs and display it in the "total" input, but this code is not working. Please help me to understand what's wrong

<table>
<tr>
<td><input name="comm" id="comm" type="number" value="10" disabled"></td>
</tr>
<tr>
<td><input name="comm" id="comm" type="number" value="5" disabled"></td>
</tr>
<tr>
<td><input name="comm" id="comm" type="number" value="4" disabled"></td>
</tr>
<tr>
<td><input name="comm" id="comm" type="number" value="10" disabled"></td>
</tr>
</table>

<input name="tot" id="tot" type="number" value="" disabled">


<script>
window.sumInputs = function() {
    var inputs = document.getElementsByTagName('input'),
        result = document.getElementById('tot'),
        sum = 0;            

    for(var i=0; i<inputs.length; i++) {
        var ip = inputs[i];

        if (ip.name && ip.name.indexOf("total") < 0) {
            sum += parseInt(ip.value) || 0;
        }

    }

    result.value = sum;
}
    </script>

Upvotes: 0

Views: 1507

Answers (1)

R&#252;zgar
R&#252;zgar

Reputation: 997

There is nothing wrong with your code, as @dfsq commented, just need to call it.

window.sumInputs = function() {
    var inputs = document.getElementsByTagName('input'),
        result = document.getElementById('tot'),
        sum = 0;            

    for(var i=0; i<inputs.length; i++) {
        var ip = inputs[i];

        if (ip.name && ip.name.indexOf("total") < 0) {
            sum += parseInt(ip.value) || 0;
        }

    }

    result.value = sum;
}
sumInputs();
<table>
<tr>
<td><input name="comm" id="comm" type="number" value="10" disabled"></td>
</tr>
<tr>
<td><input name="comm" id="comm" type="number" value="5" disabled"></td>
</tr>
<tr>
<td><input name="comm" id="comm" type="number" value="4" disabled"></td>
</tr>
<tr>
<td><input name="comm" id="comm" type="number" value="10" disabled"></td>
</tr>
</table>

<input name="tot" id="tot" type="number" value="" disabled">

IMPORTANT NOTICE : If you want to bind it to onchange="sumInputs()" function, then you must modify your code. Such as changing the line from

document.getElementsByTagName('input'),

to

document.querySelectorAll('[name="comm"]');

and all the inputs like

<input name="comm" id="comm" type="number" value="10" disabled">

to

<input onchange="sumInputs()" name="comm" id="comm" type="number" value="10" disabled">

Upvotes: 2

Related Questions