title: Update amount and total fields based on values entered in yii2
body: <p>I am working on an invoice in yii2. The invoice has <code>items</code> added dynamically using the <code>wbraganca\dynamicform\DynamicFormWidget</code>. These items each has <code>quantity</code> and <code>price</code> inputs, and an <code>amount</code> updated automatically based on the values of <code>quantity</code> and <code>price</code>. At the bottom of the invoice, is the <code>total</code> which is the sum of the <code>amount</code> of each <code>item</code> of the invoice. The <code>total</code> field is also updated automatically when any of the input fields i.e. <code>quantity</code> and <code>price</code> changes. I have tried coming up with a <code>Javascript</code> code that I got online but this only updates the first item <code>amount</code> but the rest are not working. Below is my code for the form...</p>
  
  <p><code>_form.php</code></p>
  
  <pre><code>&lt;?php
  
  use yii\helpers\Html;
  use kartik\widgets\ActiveForm;
  use wbraganca\dynamicform\DynamicFormWidget;
  use kartik\widgets\DatePicker;
  use yii\helpers\Url;
  use yii\helpers\ArrayHelper;
  use app\models\Tenant;
  use app\models\InvoiceItems;
  use app\models\FinancialAccounts;
  
  /* @var $this yii\web\View */
  /* @var $model app\models\Invoices */
  /* @var $form yii\widgets\ActiveForm */
  ?&gt;
  
  &lt;?php
  /* start getting the totalamount */
  $script = &lt;&lt;&lt;EOD
      var getAmount = function() {
  
          var qnty = $(".qnty").val();
          var price = $(".price").val();
          var amount = 0;
  
          amount = parseInt(qnty) * parseInt(price);
  
          //Assign the sum value to the field
          $(".amount").val(amount);
      };
  
      $(".price").on("change", function() {
          getAmount();
      });
  EOD;
  $this-&gt;registerJs($script);
  /*end getting the totalamount */
  ?&gt;
  
  &lt;div class="invoices-form"&gt;
  
      &lt;?php $form = ActiveForm::begin(['id' =&gt; 'dynamic-form']); ?&gt;
  
      &lt;fieldset&gt;
  
          &lt;legend&gt;Invoice Details&lt;/legend&gt;
  
          &lt;div class="form-group kv-fieldset-inline"&gt;
              &lt;div class="col-sm-3"&gt;
                  &lt;?= $form-&gt;field($modelInvoice, 'tenant_id')-&gt;dropDownList(ArrayHelper::map(Tenant::find()-&gt;select(['tenant_id', 'first_name', 'last_name', 'address'])-&gt;all(), 'tenant_id', 'displayName'),
                  [
                      'prompt'=&gt;'Select Tenant', 'class' =&gt; 'form-control inline-block',
                      'onchange'=&gt;'
                          $.post( "'.Yii::$app-&gt;urlManager-&gt;createUrl('lease/list-lease?tenant_id=').'"+$(this).val(), function( data ) {
                            $( "select#lease" ).html( data );
                          });
                      '
                  ]) ?&gt;
              &lt;/div&gt;
  
              &lt;div class="col-sm-3"&gt;
                  &lt;?php 
                  $dataLease=ArrayHelper::map(\app\models\Lease::find()-&gt;asArray()-&gt;all(), 'lease_id', 'leaseDetails');
                  echo $form-&gt;field($modelInvoice, 'lease')
                      -&gt;dropDownList(
                          $dataLease,           
                          ['id'=&gt;'lease']
                      );
              ?&gt;
              &lt;/div&gt;
  
              &lt;div class="col-sm-3"&gt;
                  &lt;?= $form-&gt;field($modelInvoice, 'date')-&gt;widget(DatePicker::classname(), ['options' =&gt; ['placeholder' =&gt; 'Enter Invoice date ...'], 'pluginOptions' =&gt; ['autoclose'=&gt;true, 'format' =&gt; 'yyyy-mm-dd', 'endDate' =&gt; '0d']]) ?&gt;
              &lt;/div&gt;
  
              &lt;div class="col-sm-3"&gt;
                  &lt;?= $form-&gt;field($modelInvoice, 'due_date')-&gt;widget(DatePicker::classname(), ['options' =&gt; ['placeholder' =&gt; 'Enter due date ...'], 'pluginOptions' =&gt; ['autoclose'=&gt;true, 'format' =&gt; 'yyyy-mm-dd', 'startDate' =&gt; '0d']]) ?&gt;
              &lt;/div&gt;
  
              &lt;div class="col-sm-3"&gt;
                  &lt;?= $form-&gt;field($modelInvoice, 'invoice_number')-&gt;textInput(['maxlength' =&gt; true]) ?&gt;
              &lt;/div&gt;
          &lt;/div&gt;        
  
      &lt;/fieldset&gt;
  
      &lt;fieldset&gt;
  
          &lt;legend&gt;Invoice Line Items&lt;/legend&gt;
  
          &lt;?php DynamicFormWidget::begin([
              'widgetContainer' =&gt; 'dynamicform_wrapper',
              'widgetBody' =&gt; '.container-items',
              'widgetItem' =&gt; '.invoice-item',
              'limit' =&gt; 10,
              'min' =&gt; 1,
              'insertButton' =&gt; '.add-item',
              'deleteButton' =&gt; '.remove-item',
              'model' =&gt; $modelsInvoiceItem[0],
              'formId' =&gt; 'dynamic-form',
              'formFields' =&gt; [
                  'Items',
              ],
          ]); ?&gt;
  
          &lt;table class="table table-bordered table-striped"&gt;
              &lt;thead&gt;
                  &lt;tr&gt;
                      &lt;th&gt;Invoice Item&lt;/th&gt;
                      &lt;th&gt;Description&lt;/th&gt;
                      &lt;th&gt;Quantity&lt;/th&gt;
                      &lt;th&gt;Price (Kshs)&lt;/th&gt;
                      &lt;th&gt;Account&lt;/th&gt;
                      &lt;th&gt;Amount&lt;/th&gt;
                      &lt;th class="text-center" style="width: 5%;"&gt;
                          &lt;button type="button" class="add-item btn btn-success btn-xs"&gt;&lt;span class="fa fa-plus"&gt;&lt;/span&gt;&lt;/button&gt;
                      &lt;/th&gt;
                  &lt;/tr&gt;
              &lt;/thead&gt;
              &lt;tbody class="container-items"&gt;
              &lt;?php foreach ($modelsInvoiceItem as $indexItem =&gt; $modelInvoiceItem): ?&gt;
                  &lt;tr class="invoice-item"&gt;
                      &lt;td class="vcenter"&gt;
                          &lt;?php
                              // necessary for update action.
                              if (! $modelInvoiceItem-&gt;isNewRecord) {
                                  echo Html::activeHiddenInput($modelInvoiceItem, "[{$indexItem}]id");
                              }
                          ?&gt;
                          &lt;?= $form-&gt;field($modelInvoiceItem, "[{$indexItem}]item_id")-&gt;label(false)-&gt;dropDownList(ArrayHelper::map(InvoiceItems::find()-&gt;select(['item_id', 'item'])-&gt;all(), 'item_id', 'item'),['class' =&gt; 'form-control inline-block', 'prompt'=&gt;'Select Invoice Item']) ?&gt;
                      &lt;/td&gt;
                      &lt;td class="vcenter"&gt;
                          &lt;?= $form-&gt;field($modelInvoiceItem, "[{$indexItem}]desc")-&gt;label(false)-&gt;textInput(['maxlength' =&gt; true]) ?&gt;
                      &lt;/td&gt;
                      &lt;td class="vcenter"&gt;
                          &lt;?= $form-&gt;field($modelInvoiceItem, "[{$indexItem}]qnty")-&gt;label(false)-&gt;textInput(['class' =&gt; 'qnty']) ?&gt;
                      &lt;/td&gt;
                      &lt;td class="vcenter"&gt;
                          &lt;?= $form-&gt;field($modelInvoiceItem, "[{$indexItem}]price")-&gt;label(false)-&gt;textInput(['class' =&gt; 'price']) ?&gt;
                      &lt;/td&gt;
                      &lt;td class="vcenter"&gt;
                          &lt;?= $form-&gt;field($modelInvoiceItem, "[{$indexItem}]account_id")-&gt;label(false)-&gt;dropDownList(ArrayHelper::map(FinancialAccounts::find()-&gt;select(['account_id', 'account_name'])-&gt;all(), 'account_id', 'account_name'),['class' =&gt; 'form-control inline-block', 'prompt'=&gt;'Select Account']) ?&gt;
                      &lt;/td&gt;
                      &lt;td class="vcenter"&gt;
                          &lt;?= $form-&gt;field($modelInvoiceItem, "[{$indexItem}]amount")-&gt;label(false)-&gt;textInput(['class'=&gt;'amount','readOnly'=&gt; true]) ?&gt;
                      &lt;/td&gt;
                      &lt;td class="text-center vcenter" style="width: 5%; verti"&gt;
                          &lt;button type="button" class="remove-item btn btn-danger btn-xs"&gt;&lt;span class="fa fa-minus"&gt;&lt;/span&gt;&lt;/button&gt;
                      &lt;/td&gt;
                  &lt;/tr&gt;
               &lt;?php endforeach; ?&gt;
              &lt;/tbody&gt;
              &lt;tbody&gt;
                  &lt;tr&gt;
                       &lt;td&gt;&lt;/td&gt;
                       &lt;td&gt;&lt;/td&gt;
                       &lt;td&gt;&lt;/td&gt;
                       &lt;td&gt;&lt;/td&gt;
                       &lt;td&gt;Total&lt;/td&gt;
                       &lt;td class="total"&gt;
                           &lt;?= $form-&gt;field($modelInvoice, "total")-&gt;label(false)-&gt;textInput(['class'=&gt;'total','readOnly'=&gt; true]) ?&gt;
                       &lt;/td&gt;
                       &lt;td&gt;&lt;/td&gt;
                   &lt;/tr&gt;
              &lt;/tbody&gt;
          &lt;/table&gt;
  
          &lt;?php DynamicFormWidget::end(); ?&gt;
  
      &lt;/fieldset&gt;
  
  
      &lt;div class="col-sm-offset-3 col-sm-9"&gt;
          &lt;?= Html::submitButton($modelInvoice-&gt;isNewRecord ? 'Create' : 'Update', ['class' =&gt; $modelInvoice-&gt;isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?&gt;
          &lt;?= Html::resetButton('Reset', ['class' =&gt; 'btn btn-default']) ?&gt;
      &lt;/div&gt;
  
      &lt;?php ActiveForm::end(); ?&gt;
  
  &lt;/div&gt;
  </code></pre>
  
  <p>Specifically, this is the <code>Javascript</code> code</p>
  
  <pre><code>&lt;?php
  /* start getting the totalamount */
  $script = &lt;&lt;&lt;EOD
      var getAmount = function() {
  
          // var items = $(".item");
          // var qnty = $(elem).find(".qnty").val();
          var qnty = $(".qnty").val();
          var price = $(".price").val();
          // var price = $(elem).find(".price").val();
          var amount = 0;
  
          amount = parseInt(qnty) * parseInt(price);
  
          // items.each(function (index, elem) {
          //     var priceValue = $(elem).find(".sumPart").val();
          //     //Check if priceValue is numeric or something like that
          //     sum = parseInt(sum) + parseInt(priceValue);
          // });
          //Assign the sum value to the field
          $(".amount").val(amount);
      };
  
      //Bind new elements to support the function too
      $(".price").on("change", function() {
          getAmount();
      });
  EOD;
  $this-&gt;registerJs($script);
  /*end getting the totalamount */
  ?&gt;
  </code></pre>
  
  <p>And here is the screenshot of the form that I am working with:
  <a href="https://i.stack.imgur.com/UDUmk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UDUmk.jpg" alt="Screen Shot of the Invoice"></a></p>
  
  <p>I am not good with <code>Javascript</code> hence I don't understand most of the code but I get the idea and flow of information. Please assist me on what I can do here.
  Thanks.</p>