Yii2-dynamicforms和javascript

前端之家收集整理的这篇文章主要介绍了Yii2-dynamicforms和javascript前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有在Yii2中工作的wbraganca动态表单,但我需要添加一个小函数来乘以2个字段并将值放在第三个中,并在每个新动态表单中执行此操作(假设字段1是价格,字段2是金额和字段3总计).
使用我的代码,我能够做到这一点,但只能在第一个动态表单上.
  1. <?PHP
  2. $script = <<< JS
  3. $('#itemsfactura-{$i}-cantidad').change(function(){
  4. var cantidad = $(this).val();
  5. var precio = $('#itemsfactura-{$i}-precio').val();
  6. $('#itemsfactura-{$i}-total_item').val(cantidad * precio);
  7. });
  8. JS;
  9. $this->registerJs($script);
  10. ?>

这是动态表单字段的代码

  1. ...
  2. <div class="row">
  3. <div class="col-sm-4">
  4. <?= $form->field($modelItemFactura,"[{$i}]precio")->textInput(['maxlength' => true]) ?>
  5. </div>
  6. <div class="col-sm-4">
  7. <?= $form->field($modelItemFactura,"[{$i}]cantidad")->textInput(['maxlength' => true]) ?>
  8. </div>
  9. <div class="col-sm-4">
  10. <?= $form->field($modelItemFactura,"[{$i}]total_item")->textInput(['maxlength' => true]) ?>
  11. </div>
  12. </div>...
形成
  1. <div class="col-sm-4">
  2. <?= $form->field($modelItemFactura,"[{$i}]precio")->textInput(['maxlength' => true,'onchange' => 'getProduct($(this))','onkeyup' => 'getProduct($(this))']) ?>
  3. </div>
  4. <div class="col-sm-4">
  5. <?= $form->field($modelItemFactura,"[{$i}]cantidad")->textInput(['maxlength' => true,'onkeyup' => 'getProduct($(this))']) ?>
  6. </div>

JS

  1. function getProduct(item) {
  2. var index = item.attr("id").replace(/[^0-9.]/g,"");
  3. var total = current = next = 0;
  4.  
  5. var id = item.attr("id");
  6. var myString = id.split("-").pop();
  7.  
  8. if(myString == "precio") {
  9. fetch = index.concat("-cantidad");
  10. } else {
  11. fetch = index.concat("-precio");
  12. }
  13.  
  14. temp = $("#itemsfactura-"+fetch+"").val();
  15.  
  16. if(!isNaN(temp) && temp.length != 0) {
  17. next = temp;
  18. }
  19.  
  20. current = item.val();
  21. if(isNaN(current) || current.length == 0) {
  22. current = 0;
  23. }
  24.  
  25. if(!isNaN(current) && !isNaN(next)) {
  26. total = parseInt(current) * parseInt(next);
  27. }
  28.  
  29. totalItem = "itemsfactura-".concat(index).concat("-total_item");
  30.  
  31. $("#"+totalItem+"").val(total);
  32. }

猜你在找的PHP相关文章