获取多行表中特定列的总价值

Get total value of a particular column in multiple row table

本文关键字:总价值 获取      更新时间:2023-09-26

我创建了一个表,可以动态地向其中添加多行。有一列是用来增加成本的。现在我想获取表底部每行的总成本值。我怎么能得到这个使用JavaScript?

这是我的html代码动态表。

<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);
        }
    });

您应该迭代属于表格的输入标记,并且id以"cost"开头。

此外,您不能将直接添加到主体,您希望将其添加到已创建的最后之后。

试试这个(edit:)

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>

希望有帮助!

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

您可以遍历输入选择器,将值聚合以获得总数。

注意:正如评论中提到的,不要对所有输入标签使用相同的id。这不是最佳实践