我的Yii2表单中有两个文本框-mrp,rate。我想要的是,当用户以mrp为单位键入金额时,将在费率中填充10%的折现值。假设用户在mrp中输入100,则rate中填充的值将为90。这将显示小数点后2位,即90.00。
我的代码如下-

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model frontend\modules\batchno\models\Productbatch */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="productbatch-form">

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'productname')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'batchno')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'mfgdate')->textInput() ?>

    <?= $form->field($model, 'expdate')->textInput() ?>

    <?= $form->field($model, 'mrp')->textInput() ?>

    <?= $form->field($model, 'rate')->textInput() ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

 <?php
    $ this->RegisterJs ( "

    $('#Productbatch-mrp').keyup(function(){
                     var total = this.value;
                     var percent = 10;
                     var discount_value = (total / 100) * percent;
                    $('#Productbatch-rate').val(discount_value);
                 });
                });

    " ,  View :: POS_END);

  ?>

最佳答案

您应该在jQuery代码选择器中尝试使用Html::getInputId($model, 'mrp')代替Productbatch-mrp。希望它能对您有所帮助。

<?php
    $this->RegisterJs ( "
    $('document').ready(function(){
        $('#".Html::getInputId($model, 'mrp')."').keyup(function(){
                     var total = this.value;
                     var percent = 10;
                     var discount_value = (total * percent) / 100 ;
                     var rate = total - discount_value;
                    $('#".Html::getInputId($model, 'rate')."').val(rate);
                 });
    });

    ", View::POS_END);
  ?>

09-26 19:07