2016-10-20 11 views
1

私はYii2で働いているwbraganca動的フォームを持っていますが、私は2つのフィールドを乗算し、3番目に値を入れ、新しい動的フォームすべてでそれを行います(フィールド1がpriceフィールド2は金額、フィールド3は合計金額)。 コードを使って、私はそれを行うことができますが、最初の動的なフォームでのみ行うことができます。Yii2-dynamicformsとjavascript

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

答えて

1

フォーム

<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); 
} 
+0

ありがとうInsane Skull!、それは完璧に動作します。私はちょうど私のインラインスクリプトを削除し、あなたを別々のファイルに入れ、ファイルを登録しました。よろしく。 –