我创建了一个表,可以在其中动态添加多行。有一个栏目可以增加成本。现在我想要 获取表底部每行的总成本值。我如何使用 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);
}
});
最佳答案
您应该迭代属于该表且具有以“cost”开头的 id 的 input 标记。
此外,您不能将行直接添加到正文,您希望将其添加到已创建的最后一个行之后。
试试这个(编辑:) 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>
希望对你有帮助!
关于javascript - 获取多行表中特定列的总值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32164194/