在yii2中从动态表单按钮调用Javascript

时间:2018-04-24 14:44:14

标签: yii2

在Yii2 Dynamic表单中,我有add-item和remove-item按钮来添加新行或删除特定行。我想要的是在点击删除项目按钮时调用javascript函数。

动态表格代码 -

<?= $form->field($modelsProductsales, "[{$i}]productname")->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productbatch::find()->orderBy('productname')->all(),'productname','productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Product', 'onchange' => 'getHsndetails($(this))'],
'pluginOptions' => [
    'allowClear' => true
],
])->label(false);
?>

<?= $form->field($modelsProductsales, "[{$i}]batchno")->widget(DepDrop::classname(), [
'options' => ['onload' => 'getProdValues($(this))','onchange' => 'getItemID($(this))'],
'pluginOptions'=>[
    'depends'=> [Html::getInputID($modelsProductsales, "[{$i}]productname")],
    'placeholder'=>'Batch',
    'url'=>Url::to(['/invoice/bills/subcat'])
]
])->label(false); ?>

<?= $form->field($modelsProductsales, "[{$i}]expdate")->label(false)->textInput(['maxlength' => true,'placeholder' => 'ExpDate','readOnly'=>true]) ?>

<?= $form->field($modelsProductsales, "[{$i}]mrp")->label(false)->textInput(['maxlength' => true,'class' => 'mrp','placeholder' => 'MRP']) ?>

<?= $form->field($modelsProductsales, "[{$i}]rate")->label(false)->textInput(['maxlength' => true,'class' => 'rate','placeholder' => 'Rate']) ?>

<?= $form->field($modelsProductsales, "[{$i}]qty")->label(false)->textInput(['maxlength' => true,'class' => 'qty','placeholder' => 'Qty']) ?>

<?= $form->field($modelsProductsales, "[{$i}]free")->label(false)->textInput(['maxlength' => true,'class' => 'free','placeholder' => 'Free']) ?>


<?= $form->field($modelsProductsales, "[{$i}]discount")->label(false)->textInput(['maxlength' => true,'class' => 'disc','placeholder' => 'Discount']) ?>


<div class="pull-right">
    <button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
    <button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>

Javascript功能

<?php
/* start getting the total amount */
$this->registerJs('
    function getSum() {
        var retailPrice = 0;
        var stockistPrice = 0;
        var sum = 0;
        var totalDiscount = 0;
        var totalMrp = 0;
        var totalCst = 0;
        var totalWbst = 0;
        var totalCstonamount = 0;
        var totalWbstonamount = 0;
        var totalCstonmrp = 0;
        var totalWbstonmrp = 0;
        var totalTaxonmrp = 0;
        var totalTaxonamount = 0;
        var totalAmountonmrp = 0;
        var totalAmountonrate = 0;
        var totalBillamountonmrp = 0;
        var totalBillamountonrate = 0;
        var igstAmount = 0;
        var cgstAmount = 0;
        var sgstAmount = 0;

        var cstperValue = $(".cstPercent").val();
        var wbstperValue = $(".wbstPercent").val();
        var selectedValue = $("input[name=taxon]:checked").val();
        //alert(selectedValue);

        var items = $(".item");

        items.each(function (index, elem) {
        var qtyValue = $(elem).find(".qty").val();
        var rateValue = $(elem).find(".rate").val();
        var discValue = $(elem).find(".disc").val();
        var mrpValue = $(elem).find(".mrp").val();
        var freeValue = $(elem).find(".free").val();
        var igstPercent = $(elem).find(".igstrate").val();
        var cgstPercent = $(elem).find(".cgstrate").val();
        var sgstPercent = $(elem).find(".sgstrate").val();



        cgstAmount = (parseFloat(cgstAmount) + ((parseFloat(qtyValue)*parseFloat(rateValue) - (parseFloat(qtyValue)*parseFloat(rateValue)*parseFloat(discValue))/100)*parseFloat(cgstPercent))/100).toFixed(2);

        sgstAmount = (parseFloat(sgstAmount) + ((parseFloat(qtyValue)*parseFloat(rateValue) - (parseFloat(qtyValue)*parseFloat(rateValue)*parseFloat(discValue))/100)*parseFloat(sgstPercent))/100).toFixed(2);

        igstAmount = (parseFloat(igstAmount) + ((parseFloat(qtyValue)*parseFloat(rateValue) - (parseFloat(qtyValue)*parseFloat(rateValue)*parseFloat(discValue))/100)*parseFloat(igstPercent))/100).toFixed(2);

        stockistPrice = (parseFloat(stockistPrice) + (parseFloat(rateValue)*parseFloat(qtyValue) - (parseFloat(rateValue)*parseFloat(qtyValue)*parseFloat(discValue))/100)).toFixed(2);

        sum = Math.round(parseFloat(stockistPrice) + parseFloat(cgstAmount) + parseFloat(sgstAmount) + parseFloat(igstAmount));

    });

   if(isNaN(sum) || sum.length == 0) {
       sum = 0;
   }
   if(isNaN(cgstAmount) || cgstAmount.length == 0) {
       cgstAmount = 0;
   }
   if(isNaN(sgstAmount) || sgstAmount.length == 0) {
       sgstAmount = 0;
   }
   if(isNaN(igstAmount) || igstAmount.length == 0) {
       igstAmount = 0;
   }
   if(isNaN(stockistPrice) || stockistPrice.length == 0) {
       stockistPrice = 0;
   }


   $(".sum").val(sum);
   $(".cgstAmount").val(cgstAmount);
   $(".sgstAmount").val(sgstAmount);
   $(".igstAmount").val(igstAmount);
   $(".totalAmount").val(stockistPrice);

   $(".billAmount").val(sum);
   $(".overdueAmount").val(sum);


    }


    $(".container-items").on("change", function() {
        getSum();
    });
    $(".remove-item").on("click", function() {
        getSum();
        alert("This Onclick is working");
    });

');
/*end getting the total amount */
?>

在更改项目时,正在调用javascript并且我获得了该值。但是在Click of the remove-item按钮上,javascript没有被调用。请让我知道如何调用onclick按钮的javascript remove-item

控制台中没有错误。

1 个答案:

答案 0 :(得分:0)

如果添加和删除字段是仅操作表单的唯一函数,则可以使用新的MutationObserver来跟踪是否在目标容器中添加或删除了任何新元素。

此新的DOM Api可在FirefoxWebkit夜间版本以及Chrome 18中使用。

  

这个新规范相对于弃用的DOM的关键优势   突变事件规范是效率之一。如果您正在观察节点   对于更改,在DOM具有之前不会触发您的回调   完成改变。触发回调时,会提供一个   DOM的更改列表,然后您可以循环访问它   选择回应。

     

这也意味着您编写的任何代码都需要处理   观察者结果是为了对您正在寻找的变化做出反应。

考虑以下使用addremove按钮在容器div中添加和删除div的示例,并使用MutationObserver查找目标元素{{}中的更改1}}并在检查Mutation事件是否为#container时更新了callback函数内的div计数,该事件是在目标容器中添加或删除子元素时触发的。

&#13;
&#13;
ChildList
&#13;
function startObserver() {
  // select the target node
  var target = document.querySelector('#container');
  
  // create an observer instance
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      if (mutation.type == 'childList') {
        $('.counter').html($("#container>div").length + ' div(s) total');
      }
    });
  });

  // configuration of the observer:
  var config = {
    childList: true,
  }

  // pass in the target node, as well as the observer options
  observer.observe(target, config);
}

jQuery(function($) {
  $("#add-more").on("click", function() {
    $("#container").append("<div>some thing " + Math.random() + "</div>")
  })

  $("#remove").on("click", function() {
    $("#container>div:eq(0)").remove()
  });

  startObserver();
});
&#13;
.counter {
  float: right;
  font-size: 2em;
  color: red;
  margin-right: 100px;
}
&#13;
&#13;
&#13;

您需要做的是将表单包装在div中并提供<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section class="section"><button id="add-more">add more</button> <button id="remove">Remove</button> <div class="counter">0 div(s) total</div> <div id='container'> </div>id并将调用添加到container内的函数getSum()功能你可以复制下面的代码。

callback

注意:如果您已将其添加到任何其他事件,请删除对$this->registerJs("// select the target node var target = document.querySelector('#container'); // create an observer instance var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (mutation.type == 'childList') { getSum(); } }); }); // configuration of the observer: var config = { childList: true}; // pass in the target node, as well as the observer options observer.observe(target, config); ", yii\web\View::POS_READY); 功能的任何其他调用

getSum()

希望这可以帮助您解决问题。