1 回答
TA贡献1865条经验 获得超7个赞
您不能在 HTML 中复制 ID。您可以将行号保存在每次添加新行时递增的变量中,并使用该变量生成 ID:
$(function() {
let row = 1;
$('#addRow').click(function() {
row++;
let temp_td = '<tr><th scope="row">' + row + '</th><td><label><input type="text" name="name"></label></td><td><label><input type="text" id="price' + row + '" oninput="calculate(' + row + ')"></td><td><input type="text" id="qt' + row + '" oninput="calculate(' + row + ')"></td><td><input type="text" id="ttl' + row + '" name="total"></td><td><button class="remove">-</button></td></tr>';
$('tbody').append(temp_td)
});
$(document).on('click', '.remove', function() {
$(this).parents('tr').remove();
});
});
function calculate(r) {
var price = document.getElementById('price' + r).value;
var qt = document.getElementById('qt' + r).value;
var ttl = document.getElementById('ttl' + r);
var multiply = price * qt;
ttl.value = multiply;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="table-responsive container">
<table class="table">
<thead class="dark">
<tr>
<th scope="col">SL.</th>
<th scope="col">Item Description</th>
<th scope="col">Price</th>
<th scope="col">Qty.</th>
<th scope="col">Total</th>
<th scope="col">Del</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td><label>
<input type="text" name="name">
</label>
</td>
<td><label>
<input type="text" id="price1" oninput="calculate(1)">
</td>
<td>
<input type="text" id="qt1" oninput="calculate(1)">
</td>
<td>
<input type="text" id="ttl1" name='total'>
</td>
<td>
<button class="remove">-</button>
</td>
</tr>
</tbody>
</table>
<button id="addRow">+ Add</button>
如果您愿意,您也可以对名称执行此操作。我在上面的代码中没有这样做,因为它对于这个答案不是必需的。
或者,您可以将元素本身传递给calculate()函数,然后使用 jQuery 查找其他“兄弟”元素。所以你根本不需要身份证。
添加回答
举报