0
2

More than 1 year has passed since last update.

javascriptでtableタグのtd内の数値の合計を自動で計算

Last updated at Posted at 2022-11-25

javascriptを使ってtableタグ内のtdに入っている値段の合計を計算する方法。
もっと効率よく綺麗に書く方法あったら教えてくださいm(_ _)m

image.png

<html>
<script type="text/javascript">
    window.onload = function () {
        var tableElem = document.getElementById('table_01');
        var rowElems = tableElem.rows;
        var price = 0;
        for (i = 0, len = rowElems.length - 1; i < len; i++) {
            price += parseInt(rowElems[i].cells[1].innerText);
        }
        document.getElementById('goukei').innerText = price;
    }
</script>
<body>
    <TABLE id="table_01">
        <TR>
            <td>りんご</td>
            <td>300</td>
        </TR>
        <TR>
            <td>バナナ</td>
            <td>400</td>
        </TR>
        <TR>
            <td>いちご</td>
            <td>500</td>
        </TR>
        <TR>
            <td>合計</td>
            <td id="goukei"></td>
        </TR>
    </TABLE>
</body>
</html>
0
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2