获取多行中特定列的总值 table

Get total value of a particular column in multiple row table

我创建了一个 table,我可以在其中动态添加多行。有一列可以添加成本。现在我想 获取 table 底部每一行的总成本值。我如何使用 JavaScript 获得此信息?

这是我的 html 动态代码 table。

<table>
    <thead>
        <tr>
            <th>No</th>
            <th>Title</th>
            <th cost</th>
        </tr>
    </thead>
    <tbody id="body">

        <tr>
            <th>1</th>
            <td>
                <input type="text"  id="title" name="title[]" />
            </td>
            <td>
                <input type="text"  id="cost" name="cost[]" />
            </td>
        </tr>
    </tbody>        
</table>

Javascript函数:

$(function(){
        $('.addrow').click(function(){
            addrow();
        });


        function addrow()
        {

            var row =($('#body tr').length-0)+1;
            var tr ='<tr>'+
                '<th>'+row+'</th>'+
                '<td><input type="text" id="title" name="title[]" ></td>'+
                '<td><input type="text"  id="cost" name="cost[]" /></td>'+
                '</tr>';
            $('#body').append(tr);
        }
    });

如果仅使用文本输入,请尝试使用 https://api.jquery.com/input-selector/ 获取所有输入选择器。

您可以遍历输入选择器,汇总这些值以获得总数。

注意:如评论中所述,不要对所有输入标签使用相同的 ID。这不是最佳做法

您应该迭代属于 table 的 input 标签,并且具有以 [=40= 开头的 id ].

还有,不能直接把加到正文,要在最后后面加]行已创建。

试试这个(编辑:fiddle(旧习难改)片段。

$(document).ready(function(){
        $('#addRow').click(function(){
            addRow();
        });
        $('#totalRow').click(function(){
            totalRow();
        });


        function addRow()
        {
            var rowId = $('#myTable tr').length;
   $('#myTable > tbody:last-child').append(
       '<tr><th>' + rowId + ' </th>' +
       '<td><input type="text"  id="title' + rowId + '" /></td>' +  
                '<td><input type="text"  id="cost' + rowId + '"</td></tr>'
   );
    }
    
        function totalRow()
        {
            var rowId = $('#myTable tr').length;
            var val = 0;
             $("#myTable [id^=cost]").each(function() {      
       val += parseFloat($(this).val());
    });
   $('#myTable > tbody:last-child').append(
       '<tr><th>T</th>' +
       '<td><input type="text" id="totalRow" value="TOTAL" /></td>' +  
                '<td><input type="text" id="totalCost" value="' + val +'" /></td></tr>'
   );
  }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addRow">Add row</div>
<div id="totalRow">Calculate total row</div>
<br>
<table id="myTable">
    <thead>
        <tr>
            <th>No</th>
            <th>Title</th>
            <th>Cost</th>
        </tr>
    </thead>
    <tbody> 
        <tr>
            <th>1</th>
            <td>
                <input type="text"  id="title1" value="Example" />
            </td>
            <td>
                <input type="text"  id="cost1" value="25" />
            </td>
        </tr>
    </tbody>        
</table>

希望对您有所帮助!