简体   繁体   中英

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>

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">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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