计算3个字段并以yii2动态形式显示第4个结果

时间:2017-01-28 10:21:50

标签: yii2

我正在尝试以yii2动态形式计算3个字段的总和 - si_mrp + si_discp + si_taxpc。这与Calculate from 3 inputfield in dynamic form yii2的解决方案相同。但目前的解决方案不起作用。 表格字段

<?= $form->field($modelsProductsales, "[{$i}]si_mrp")->label(false)->textInput(['maxlength' => true,'onchange' => 'getUdisc($(this))', 'onkeyup' => 'getUdisc($(this))','class' => 'mrp','placeholder' => 'MRP']) ?>
<?= $form->field($modelsProductsales, "[{$i}]si_discp")->label(false)->textInput(['maxlength' => true,'onchange' => 'getUdisc($(this))', 'onkeyup' => 'getUdisc($(this))','class' => 'discp','placeholder' => 'Disc %']) ?>
<?= $form->field($modelsProductsales, "[{$i}]si_taxpc")->label(false)->textInput(['maxlength' => true,'onchange' => 'getUdisc($(this))', 'onkeyup' => 'getUdisc($(this))','class' => 'taxpc','placeholder' => 'Tax %']) ?>
<?= $form->field($modelsProductsales, "[{$i}]si_rate")->label(false)->textInput(['maxlength' => true,'class' => 'rate','placeholder' => 'Rate']) ?>


javascript code - 
<?php
/* start getting the rate */
$script = <<< JS
function getUdisc(item) {
    var index  = item.attr("id").replace(/[^0-9.]/g, "");
    var total = current = next = previous = 0;

    var id = item.attr("id");
    var myString = id.split("-").pop();

    if (myString == "si_mrp") {
        fetch1 = index.concat("-si_discp");
        fetch2 = index.concat("-si_taxpc");
    } else if (myString == "si_discp") {
        fetch1 = index.concat("-si_mrp");
        fetch2 = index.concat("-si_taxpc");
    } else {
        fetch1 = index.concat("-si_discp");
        fetch2 = index.concat("-si_mrp");
    }

    temp1 = $("#sellitem-"+fetch1+"").val();
    temp2 = $("#sellitem-"+fetch2+"").val();

    if (!isNaN(temp1) && temp1.length != 0) {
        next = temp1;
    }

    if (isNaN(temp2) || temp2.length == 0) {
        previous = temp2;
    }

    current = item.val();
    if (isNaN(current) || current.length == 0) {
        current = 0;
    }

    if (!isNaN(current) && !isNaN(next) && !isNaN(previous)) {
        total = (parseFloat(current) + parseFloat(next) + parseFloat(previous)).toFixed(2);
    }

    udiscField = "sellitem-".concat(index).concat("-si_rate");

    $("#"+udiscField+"").val(total);
}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the rate */
?>

错误 si_mrp字段似乎没有加起来

但是,当我进行以下计算时

total = (parseFloat(10.5) + parseFloat(11.5) + parseFloat(12.5)).toFixed(2);

我得到了正确的结果。

我再次看到,si_mrp + si_discpsi_discp + si_taxpc正在发生但不是si_mrp + si_discp + si_taxpc 不确定此代码有什么问题。请帮忙。

1 个答案:

答案 0 :(得分:1)

更新此内容:

if (isNaN(temp2) || temp2.length == 0) {
    previous = temp2;
}

if(!isNaN(temp2) && temp2.length != 0) {
    previous = temp2;
}