![](/img/trans.png)
[英]How to get the Table Ids and the Value on clicking a row element in a particular column from multiple tables?
[英]Get total value of a particular column in multiple row table
我創建了一個表,可以在其中動態添加多行。 有一個列會增加成本。 現在,我想在表格底部獲取每一行的總成本值。 如何使用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);
}
});
如果僅使用文本輸入,請嘗試使用https://api.jquery.com/input-selector/獲取所有輸入選擇器。
您可以遍歷輸入選擇器,匯總值以得出總計。
注意:如注釋中所述,請勿對所有輸入標簽使用相同的ID。 這不是最佳實踐
您應該迭代屬於該表並具有以“ cost”開頭的id的輸入標簽。
此外,您不能將行直接添加到主體 ,而要在已創建的最后一行之后添加。
試試這個( 編輯:) 小提琴 (舊習慣很難解決)摘要。
$(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>
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.