0

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>
Sergi Khizanishvili
  • 537
  • 1
  • 7
  • 16

1 Answers1

2

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">
Rüzgar
  • 947
  • 9
  • 20
  • 1
    Consider keeping your markup free of inline javascript calls as this answer suggests. There are advantages and disadvantages to calling your javascript inline, as discussed in this SO post: [inline vs external script](http://stackoverflow.com/questions/29918246/javascript-inline-vs-external-script-whats-the-difference). IMHO, keeping your markup and your javascript clearly separated is a better practice due to increased flexibility and maintainability. – McHat Apr 11 '17 at 19:06