如何在for循环中的输入元素上使用Javascript函数。德扬戈
我正在开发一个Django表单,它可以实时计算值。我希望javascript函数适用于所有行,每行由3个输入字段组成。我尝试为每个输入字段分配一个id,后跟一个forloop计数器。我还循环使用了这个函数,希望它能适用于所有ID,a1,a2,a3。。。b1,b2,b3。。。c1,c2,c3。。。 但是,该函数仅适用于最后一行 以下是我使用的javascript:如何在for循环中的输入元素上使用Javascript函数。德扬戈,javascript,python,django,Javascript,Python,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 < {{ tota
<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>
对于(i=0;i<{{total_rows | safe}};i++){
$('input').keyup(函数(){
var firstValue=Number($('#a'+i.val());
var secondValue=Number($('#b'+i.val());
document.getElementById('c'+i).value=firstValue*secondValue;
});
}
这是我的模板:
<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>
{%csrf_令牌%}
量
单价
数量
{项目的百分比,循环中的金额\u列表%}
{%endfor%}
将所有输入多次绑定到多个键控处理程序。但是,您不需要在这里使用ID;在JavaScript中循环行。我在这里简化了一点标记
(但是,如果您计划将此表单发回Django,则每个输入需要有唯一的名称
s!)
将所有输入多次绑定到多个键控处理程序。但是,您不需要在这里使用ID;在JavaScript中循环行。我在这里简化了一点标记 (但是,如果您计划将此表单发回Django,则每个输入需要有唯一的
名称
s!)
{% 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);
});