我正在制作一個條目串列,該串列將自動添加金額并在底部顯示總金額。我正在嘗試將 onchange 實作到函式中,但不確定如何執行。如果值是固定的并且需要重繪 頁面,我當前的代碼只會總結數量。
提前致謝。
var rows = $("#data tr:gt(0)");
var tamount;
rows.children("td:nth-child(3)").each(function() {
tamount = parseInt($(this).html());
});
$("#total_amount").html(tamount);
| No | Description | Amount |
| -- | ----------- | ------ |
| 1 | abc | 2.50 |
| 2 | efg | 1.90 |
| 3 | tyu | 5.00 |
| 4 | mno | 7.90 |
--------------------
Total Amount : 17.30
--------------------
<table id="data">
<tr>
<th>No</th>
<th>Description</th>
<th>Amount</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" name="descrpt"></td>
<td><input type="number" name="amount"></td>
</tr>
<tr>
<td>2</td>
<td><input type="text" name="descrpt"></td>
<td><input type="number" name="amount"></td>
</tr>
<tr>
<td>3</td>
<td><input type="text" name="descrpt"></td>
<td><input type="number" name="amount"></td>
</tr>
</table>
<div>
<h5>Total Amount :<input type="number" name="total_amount" readonly></h5>
</div>
uj5u.com熱心網友回復:
在你的 javascript 中試試這個代碼:
$(document).ready(function () {
$('input[name="total_amount"]').val(calcSum());
$('input[name="amount"]').change(function () {
$('input[name="total_amount"]').val(calcSum());
});
});
function calcSum() {
var tamount = 0;
$('input[name="amount"]').each(function() {
tamount = parseInt(($(this).val() ? $(this).val() : 0));
});
return tamount;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="data">
<tr>
<th>No</th>
<th>Description</th>
<th>Amount</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" name="descrpt"></td>
<td><input type="number" name="amount"></td>
</tr>
<tr>
<td>2</td>
<td><input type="text" name="descrpt"></td>
<td><input type="number" name="amount"></td>
</tr>
<tr>
<td>3</td>
<td><input type="text" name="descrpt"></td>
<td><input type="number" name="amount"></td>
</tr>
</table>
<div>
<h5>Total Amount :<input type="number" name="total_amount" readonly></h5>
</div>
解釋:
- 而不是獲取子元素,您可以直接使用
$('input[name="amount"]')來參考每個輸入元素 $('input[name="amount"]').each()將遍歷每個數字欄位- 我創建了一個新函式
calcSum()來完成計算部分。 - 您應該使用
.val()for 輸入元素而不是.html() - 注意,
change()將要求您從該領域失去焦點,或者,您可以使用keyup()
無需更改 html。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/329287.html
上一篇:CSS過渡不起作用,它以前作業過
