I have an HTML table fetching values dynamically from the database and I have used the sum function to calculate the sum of entire column.
These are my columns where I am fetching the sum total of a column
<td id="totalValue13" style="background-color: darkseagreen;"></td>
<td id="totalValue11" style="background-color: darkseagreen;"></td>
<td id="totalValue12" style="background-color: darkseagreen;"></td>
I want to pass the value of these <td>
s into a textbox where I want to calculate these three values. I am using JavaScript to calculate it, given below is a JavaScript code for calculations:
<script type="text/javascript">
function calculate() {
var result = document.getElementById('result');
var el, i = 0, total = 0;
while (el = document.getElementById('v'+(i++))) {
el.value = el.value.replace(/\\D/, "");
total = total + Number(el.value);
}
result.value = total;
if (document.getElementById('v0').value == "" && document.getElementById('v1').value == "" && document.getElementById('v2').value == "") {
result.value = "";
}
}
</script>
I just want to know how to pass the id of an HTML table column here. Thanks.
Use .innerHTML
instead of .value
since table cells don't have a value. Here is an example on how to calculate the sum of given table cells with each having a separate id
.
function calculate() { var result = document.getElementById('result'); var v1 = document.getElementById('totalValue11'); var v2 = document.getElementById('totalValue12'); var v3 = document.getElementById('totalValue13'); var el, sum = 0; var inputList = [v1,v2,v3]; for(var i=0; i<inputList.length; i++) { el = inputList[i]; if(el.innerHTML != '' && !isNaN(el.innerHTML)) { sum += parseFloat(el.innerHTML); } } result.value = sum; // If needed to write to cell use result.innerHTML = sum; } // Call it whenever you like calculate();
td { background-color: darkseagreen; }
<table> <tr> <td id="totalValue13">5</td> <td id="totalValue11">3</td> <td id="totalValue12">25</td> </tr> <tr> <td colspan="2"><label for="result">Result:</label><input type="text" id="result" value="" readonly="readonly"></td> </tr> </table>
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.