How to sum a single table column using Javascript?

后端 未结 2 1616
梦谈多话
梦谈多话 2021-01-02 16:08

I have a generated table on my JSP that contains data for transactions: each individual transaction is a row, and there\'s a column for category, amount, type, and descripti

相关标签:
2条回答
  • 2021-01-02 17:04

    Your variable tds 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're better off summing this up using a JS framework or using a counter in JSP. Custom scripts require some effort to maintain.

    0 讨论(0)
  • 2021-01-02 17:11

    I have no knowledge about JSP but i assume that Roman C is right.

    But if you wan't to solve this 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 a jsfiddle https://jsfiddle.net/4cetuvno/1/

    0 讨论(0)
提交回复
热议问题