How to sum a single column of a table using javascript?

I have a generated table on my JSP that contains data for transactions: each individual transaction is a row, as well as a column for the category, quantity, type and description.

<table class="table table-striped" id="res"> <tr> <th>Category</th> <th>Amount</th> <th>Type</th> <th>Description</th> </tr> <c:forEach var="element" items="${sessionScope.pick}"> <tr> <td><c:out value="${element.category}" /></td> <td class="countable"> <fmt:formatNumber type="currency" currencyCode="USD" value="${element.amount}"></fmt:formatNumber> </td> <td><c:out value="${element.entry_Type}" /></td> <td><c:out value="${element.description}" /></td> </tr> </c:forEach> </table> 

So it looks like

Category ____ Quantity ____ ____ Type Description

My table is populated with Struts: I select a department in another JSP, then press "display" to go to the page that generates the table. Because of this, the table will not necessarily have a certain number of rows. What I'm trying to do is add the Amount column from each transaction so that I can display the total. I tried to do this using Javascript, but this did not work for me:

 <script src="http://code.jquery.com/jquery-2.1.4.min.js"> var cls = document.getElementById("res").getElementsByTagName("td"); var sum = 0; for (var i = 0; i < cls.length; i++){ if(tds[i].className == "countable"){ sum += isNaN(cls[i].innerHTML) ? 0 : parseInt(cls[i].innerHTML); } } document.getElementById("res").innerHTML.append("<tr><td> Total Balance </td><td>" + sum + "</td><td></td><td></td></tr>"); </script> 

Can anyone see where I messed up, or what could be a better option? Also, is there a way to sum the columns and display the total without adding another row to the table? That would be ideal if possible.

+6
source share
2 answers

Your tds variable should be named cls . Here is a working example.

https://jsfiddle.net/34wf5gzs/

 for (var i = 0; i < cls.length; i++){ if(cls[i].className == "countable"){ sum += isNaN(cls[i].innerHTML) ? 0 : parseInt(cls[i].innerHTML); } } 

Roman C is right, though . You should better summarize this using the JS framework or use the counter in the JSP. Custom scripts require some effort to maintain.

+2
source

I do not know about JSP, but I assume Roman C is right.

But if you haven't solved it with javascript, here is a working example:

 var sum = 0; var table = document.getElementById("res"); var ths = table.getElementsByTagName('th'); var tds = table.getElementsByClassName('countable'); for(var i=0;i<tds.length;i++){ sum += isNaN(tds[i].innerText) ? 0 : parseInt(tds[i].innerText); } var row = table.insertRow(table.rows.length); var cell = row.insertCell(0); cell.setAttribute('colspan', ths.length); var totalBalance = document.createTextNode('Total Balance ' + sum); cell.appendChild(totalBalance); 

Link to jsfiddle https://jsfiddle.net/4cetuvno/1/

+2
source

All Articles