[英]How to use Javascript function on input elements in a for loop. Django
我正在開發一個可以實時計算值的 Django 表單。 我希望 javascript 函數適用於每行包含 3 個輸入字段的所有行。 我嘗試為每個輸入字段分配一個 id,后跟一個 forloop 計數器。 我還遍歷了該函數,希望它適用於所有 id,a1,a2,a3... b1,b2,b3... c1,c2,c3... 但是,該函數僅適用於最后一行.
這是我使用的javascript:
<script type="text/javascript">
for (i = 0; i < {{ total_rows|safe }}; i++) {
$('input').keyup(function(){
var firstValue = Number($('#a'+i).val());
var secondValue = Number($('#b'+i).val());
document.getElementById('c'+i).value = firstValue * secondValue;
});
}
</script>
這是我的模板:
<form>
{% csrf_token %}
<table>
<thead>
<tr>
<th>Quantity</th>
<th>Unit Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
{% for item, amount in loop_list %}
<tr>
<td>
<input id="a{{ forloop.counter }}" type="text" class="form-control" placeholder="" name="quantity1" value="{{ item.quantity }}">
</td>
<td>
<input id="b{{ forloop.counter }}" type="text" class="form-control" placeholder="" name="unit_price1" value="{{ item.product.unit_price }}">
</td>
<td>
<input id="c{{ forloop.counter }}" type="text" class="form-control" placeholder="{{ amount }}" readonly>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
您將所有輸入多次綁定到多個 keyup 處理程序。 但是,您不需要在此處使用 id; 遍歷 JavaScript 中的行。 我在這里稍微簡化了標記。
(但是,如果您打算將此表單發回 Django,則每個輸入都需要有唯一的name
!)
{% for item, amount in loop_list %}
<tr class="calc-row">
<td>
<input class="quantity" value="{{ item.quantity }}">
</td>
<td>
<input class="unit-price" value="{{ item.product.unit_price }}">
</td>
<td>
<input class="amount" readonly>
</td>
</tr>
{% endfor %}
設置好類后,您可以只綁定一次數量和單價輸入,並讓事件處理程序查找每行的元素。
$("input.quantity, input.unit-price").keyup(function() {
var $row = $(this).closest("tr.calc-row");
var quantity = Number($row.find(".quantity").val());
var unitPrice = Number($row.find(".unit-price").val());
$row.find(".amount").val(quantity * unitPrice);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.