使用JS计算值到表单字段中的值

时间:2016-03-01 05:30:11

标签: javascript yii2

我有六个可在我的Yii2表单小部件中编辑的字段。我想要做的是,一旦我将整数值输入到可编辑字段中,根据给定的输入自动计算“绿叶净重”。我的编码完美无缺。但问题是如果我在字段中更改已经输入的值,它将不会更新“绿叶净重”只读字段。

$(document).ready(function(){
  var A = $('#A');
  var B = $('#B');
  var C = $('#C');
  var D = $('#D');
  var E = $('#E');

   E.change(function(e){
     var result = ((A.val() - B.val()) * C.val())/100;
     var result2 = ((A.val() - B.val()) * D.val()) / 100;
     var final = ((A.val() - B.val()) - result - result2) - E.val(); 
     Math.round(final);
     $('#F').val(final);
   })

 });

我的表格小部件编码(更新的代码)

 <?php $form = ActiveForm::begin(); ?>
 <?= $form->field($model, 'Gross_weight',[
        'feedbackIcon' => [
         'default' => 'shopping-cart',
         'success' => 'ok',
         'error' => 'exclamation-sign',

        ]
   ])->textInput(['id' => 'A', **'class' => 'factors'** ]) ?>

<div class="panel panel-primary" style="padding: 10px;">

    <div style="text-align: center; color: #008000;"><b>Deductions</b></div>

<?= $form->field($model, 'Bags_count',[
        'feedbackIcon' => [
         'default' => 'shopping-cart',
         'success' => 'ok',
         'error' => 'exclamation-sign',
        ]
   ])->textInput() ?>

<?= $form->field($model, 'Bags_weight',[
        'feedbackIcon' => [
         'default' => 'shopping-cart',
         'success' => 'ok',
         'error' => 'exclamation-sign',

        ]
   ])->textInput(['id' => 'B', **'class' => 'factors'** ]) ?>

<?= $form->field($model, 'Course_leaf',[
        'feedbackIcon' => [
         'default' => 'shopping-cart',
         'success' => 'ok',
         'error' => 'exclamation-sign',

        ]
   ])->textInput(['id' => 'C', **'class' => 'factors'**]) ?>

<?= $form->field($model, 'Water',[
        'feedbackIcon' => [
         'default' => 'shopping-cart',
         'success' => 'ok',
         'error' => 'exclamation-sign',

        ]
   ])->textInput(['id' => 'D', **'class' => 'factors'**]) ?>

<?= $form->field($model, 'Boiled_leaf',[
        'feedbackIcon' => [
         'default' => 'shopping-cart',
         'success' => 'ok',
         'error' => 'exclamation-sign',

        ]
   ])->textInput(['id' => 'E',**'class' => 'factors'**]) ?>
</div>
<?= $form->field($model, 'Greanleaf_net_weight',[
        'feedbackIcon' => [
         'default' => 'shopping-cart',
         'success' => 'ok',
         'error' => 'exclamation-sign',
        ]
   ])->textInput(['disabled' => 'disabled', 'id' => 'F']) ?>

form wiget

谢谢大家。

1 个答案:

答案 0 :(得分:1)

为了对所有输入字段的更改执行计算,您必须向所有输入字段添加一个类,并将该类用作更改事件的jQuery选择器。

 <input id="A" class="factors" ... />
 ...
 ...

 $(".factors").change(function(e) {
   ...
   ...
 }

See Demo