Yii2动态表单和javascript

Yii2动态表单和javascript,javascript,yii2,Javascript,Yii2,我有wbraganca动态表单在Yii2中工作,但我需要添加一个小函数,将两个字段相乘,并将值放入第三个字段,然后在每个新的动态表单中都这样做(假设字段1是价格,字段2是金额,字段3是总计)。 用我的代码,我可以做到这一点,但只有在第一个动态表单上 <?php $script = <<< JS $('#itemsfactura-{$i}-cantidad').change(function(){ var cantidad = $(this).val();

我有wbraganca动态表单在Yii2中工作,但我需要添加一个小函数,将两个字段相乘,并将值放入第三个字段,然后在每个新的动态表单中都这样做(假设字段1是价格,字段2是金额,字段3是总计)。 用我的代码,我可以做到这一点,但只有在第一个动态表单上

<?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);
?>

这是动态表单字段的代码:

...
<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>

谢谢你这个疯子!,它工作完美无瑕。我刚刚删除了我的内联脚本,将您的脚本放在一个单独的文件中,并注册了该文件。当做
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);
}