Yii2-dynamicforms和javascript [英] Yii2-dynamicforms and javascript
本文介绍了Yii2-dynamicforms和javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有在Yii2中工作的wbraganca动态表单,但是我需要添加一个小函数来乘以2个字段并将值放在第三个中,并在每个新动态表单中执行此操作(假设字段1是价格,字段2是金额和字段3是总的)。
使用我所拥有的代码,我只能在第一个动态表单上执行此操作。
I have wbraganca dynamic forms working in Yii2, but I need to add a little function to multiply 2 fields and put value in a third, and do that in every new dynamic form (suppose field 1 is price, field 2 is amount and field 3 is total). With the code I have I'm able to do that but only on the first dynamic form.
<?php
$script = <<< JS
$('#itemsfactura-{$i}-cantidad').change(function(){
var cantidad = $(this).val();
var precio = $('#itemsfactura-{$i}-precio').val();
$('#itemsfactura-{$i}-total_item').val(cantidad * precio);
});
JS;
$this->registerJs($script);
?>
这是动态表单字段的代码:
This is the code for the dynamic form fields:
...
<div class="row">
<div class="col-sm-4">
<?= $form->field($modelItemFactura, "[{$i}]precio")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelItemFactura, "[{$i}]cantidad")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelItemFactura, "[{$i}]total_item")->textInput(['maxlength' => true]) ?>
</div>
</div>...
推荐答案
表格
<div class="col-sm-4">
<?= $form->field($modelItemFactura, "[{$i}]precio")->textInput(['maxlength' => true, 'onchange' => 'getProduct($(this))', 'onkeyup' => 'getProduct($(this))']) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelItemFactura, "[{$i}]cantidad")->textInput(['maxlength' => true, 'onchange' => 'getProduct($(this))', 'onkeyup' => 'getProduct($(this))']) ?>
</div>
JS
function getProduct(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var total = current = next = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
if(myString == "precio") {
fetch = index.concat("-cantidad");
} else {
fetch = index.concat("-precio");
}
temp = $("#itemsfactura-"+fetch+"").val();
if(!isNaN(temp) && temp.length != 0) {
next = temp;
}
current = item.val();
if(isNaN(current) || current.length == 0) {
current = 0;
}
if(!isNaN(current) && !isNaN(next)) {
total = parseInt(current) * parseInt(next);
}
totalItem = "itemsfactura-".concat(index).concat("-total_item");
$("#"+totalItem+"").val(total);
}
这篇关于Yii2-dynamicforms和javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文