使用VueJS 2.5.17自动计算动态形式的表单字段值

时间:2019-02-27 08:33:01

标签: javascript html5 vuejs2 bootstrap-modal

我有一个包含四个输入字段的动态表单,可以添加新行或删除行。

单击“付款”按钮时将添加第一行;单击“付款”按钮后,onGetModalAddRow()函数将运行,并显示一个模式,该模式的初始表单行包含4个输入字段,其中预定义了subTotal和amountPaid字段,允许我添加新行或删除行。

每一行的表单字段是: 小计: 支付的金额: 平衡: paymentMethod:

我想要实现的目标:

当单击addRow按钮时,我希望它使上一行中的toBalance金额成为新行的subTotal和amountPaid,以此类推,将toBalance的金额设为零。

禁用上一行中的removeRow按钮的功能也是一项新增功能:这将迫使用户有序地删除行,以保持准确的计算。

但是,如果有更好的方法允许用户删除任何行(第一行除外),并且仍然可以准确计算表单字段的值,那么将不胜感激。

请检查以下代码,以便更好地理解: HTML:

付款按钮

<li><button type="button" v-on:click="onGetModalAddRow('splitpayments')" class="btn waves-effect waves-light btn-success"  data-toggle="modal" data-target="#getPayFormModal" data-whatever="@getbootstrap" title="Make Payment" >PAY</button></li>

付款明细模态表

    <!-- /. START MODAL -->
    <!-- START SPLIT PAYMENT FORM INIT -->
    <div class="modal fade" id="getPayFormModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel1">
                      <div class="modal-dialog" role="document">

                          <div class="modal-content">
                           <div class="modal-header">
     <h4 class="modal-title" id="exampleModalLabel1" >PAYMENT DETAILS</h4>
  <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                          </div>

         <div class="modal-body">
          <form class="vld-parent" ref="formContainer">

<input type="hidden" class="colorfieldblue" name="customer_amount_paid" id="customer_amount_paid" v-model="maincartsection.customer_amount_paid" :value="computeCustomerSubTotal" required />

<div v-for="(itm, index) in maincartsection.splitpaymentformitems.items" :id="index">
    <a v-on:click="removeRow(index)" style="color: red; cursor: pointer;" title="Remove Row" data-toggle="tooltip" data-original-title="Close"> <i class="fa fa-close text-danger"></i> </a>

<div class="form-group" >

<div class="row">
<div :class="{'col-6':'col-6','error': errors.has('subtotal_' + itm.id)}" >

 <label :for="'subtotal'+itm.id" class="control-label">Sub Total:</label>

<input type="text" class="form-control input"  :id="'subtotal'+index" :key="itm.id" :name="'subtotal_' + itm.id" v-validate="'required|min:3'" v-model="maincartsection.splitpaymentformitems.items[index].subtotal" :value="computeCustomerSubTotal" required  placeholder="0"  disabled="disabled" >

<div class="help-block"><ul role="alert"><li v-text="errors.first('subtotal_' + itm.id)"></li></ul></div>

<div class="help-block" style="color: #dd4b39;" ><ul role="alert"><li ></li></ul></div>
 </div>

<div :class="{'col-6':'col-6','error': errors.has('amountpaid_' + itm.id)}" >

<label :for="'amountpaid'+itm.id" class="control-label">Amount Paid:</label>

 <input type="text" class="form-control input"  :id="'amountpaid'+index" :key="itm.id" :name="'amountpaid_' + itm.id" v-validate="'required'" v-model="maincartsection.splitpaymentformitems.items[index].amountpaid"  required placeholder="0.00" v-on:change="onAmountEntered(index)" @focus="onAmountPaidFieldFocus(index)" >

 <div class="help-block"><ul role="alert"><li v-text="errors.first('amountpaid_' + itm.id)"></li></ul></div>

<div class="help-block" style="color: #dd4b39;" ><ul role="alert"><li ></li></ul></div>
</div>


</div>

</div>



<div class="form-group" >

<div class="row">

<div :class="{'col-6':'col-6','error': errors.has('tobalance_' + itm.id)}" >

<label :for="'tobalance'+itm.id" class="control-label">To Balance:</label>

<input type="text" class="form-control input"  :id="'tobalance'+index" :key="itm.id" :name="'tobalance_' + itm.id" v-validate="'required'" v-model="maincartsection.splitpaymentformitems.items[index].tobalance" :value="computeToBalance" required  placeholder="0"  disabled="disabled" >


<div class="help-block"><ul role="alert"><li v-text="errors.first('tobalance_' + itm.id)"></li></ul></div>

<div class="help-block" style="color: #dd4b39;" ><ul role="alert"><li ></li></ul></div>
</div>


 <div :class="{'col-6':'col-6','error': errors.has('paymentmethod_' + itm.id)}" >

 <label :for="'paymentmethod'+itm.id" class="control-label">Payment Method:</label>

<select class="custom-select col-12 input" :id="'paymentmethod'+index" :key="itm.id" :name="'paymentmethod_' + itm.id" v-validate="'required'" v-model="maincartsection.splitpaymentformitems.items[index].paymentmethod" required>

<option v-for="(paymntoptn, index) in items.availablepaymentoptions" :value="paymntoptn.payment_title_slug" v-text="paymntoptn.payment_title"></option>

 </select>


<div class="help-block"><ul role="alert"><li v-text="errors.first('paymentmethod_' + itm.id)"></li></ul></div>

<div class="help-block" style="color: #dd4b39;" ><ul role="alert"><li ></li></ul></div>
 </div>
</div>

</div>


<hr style="background-color: #009efb;" />

</div>

</form>
</div>

<div class="modal-footer">
 <button type="button" style="margin-right: 30%;" class="btn btn-danger waves-effect text-left" data-dismiss="modal">CANCEL</button>

<button type="button" v-on:click="addRow()" title="Split Payment" class="btn btn-info waves-effect waves-light" style="float: right; margin-right: 3%;"><i class="fa fa-plus"></i></button> 

<button type="button" :disabled="errors.any()"  class="btn btn-success">PAY NOW</button>
                                            </div>
                                        </div>

                                    </div>
                                </div>
                                <!-- END SPLIT PAYMENT FORM INIT -->
                                <!-- /. END MODAL -->

JAVASCRIPT(VueJs):

//Start Modal

    onGetModalAddRow: function (modalformdatasection) {
        self = this;
        //Empty previous modalformdata array, then Add new rows for current form data
        self.validations.fieldstatuslogs = [];
        self.maincartsection.splitpaymentformitems.items = [];
        self.maincartsection.splitpaymentformitems.id = 0;


        //Start splitpayments
        if (modalformdatasection == "splitpayments") {

            self._addRowHelper(self.computeCustomerSubTotal, self.computeCustomerSubTotal, self.computeToBalance, '');

        }
        //End splitpayments

    },
    //End Modal

    //Start addRow Helper Function
    _addRowHelper: function(newSubTotal, amountpaid, tobalance,  paymentmethod){

        //START ADD ANOTHER ROW
        self.maincartsection.splitpaymentformitems.items.push({ id: self.maincartsection.splitpaymentformitems.id++, subtotal: newSubTotal, amountpaid: amountpaid, tobalance: tobalance, paymentmethod: paymentmethod });

        self.validations.fieldstatuslogs.push({
            subtotal: {
                is_valid: true,
                text: ''
            },
            amountpaid: {
                is_valid: true,
                text: ''
            },
            tobalance: {
                is_valid: true,
                text: ''
            },

            paymentmethod: {
                is_valid: true,
                text: ''
            },
        });
        //END ADD ANOTHER ROW

    },
    //End addRow Helper Function




                //START SPLIT PAYMENT - addRow Function
    addRow: function(){

    self = this;
    var lastiteminarrayIndex = '';

    if(self.maincartsection.splitpaymentformitems.items.length < 1){
     // alert('First Item Added');
     //Disable Amount Paid Feild
        //document.getElementById('customer_amount_paid').focus();

     //self.splitPaymentClicked = true;
     self.maincartsection.splitpaymentformitems.splitPaymentStatus = 1;
      //Initialize First Item Value with Cart Value

    //Call onGetModalAddRow Function to Initialize First Item Value with Cart Value
    self.onGetModalAddRow('splitpayments');

      return;
    }

    lastiteminarrayIndex = self.maincartsection.splitpaymentformitems.items.length-1;
    var subTotalOfIndex = parseFloat(document.getElementById('subtotal'+lastiteminarrayIndex).value);

    if(!parseFloat(document.getElementById('amountpaid'+lastiteminarrayIndex).value )){
      alert('Amount Paid must be a Number and Can not be less than 1');
      return;
     }

    var amountPaidOfIndex = parseFloat(document.getElementById('amountpaid'+lastiteminarrayIndex).value);



    var newSubTotal = subTotalOfIndex - amountPaidOfIndex;

    //set value of tobalance in lastindex
    document.getElementById('tobalance'+lastiteminarrayIndex).value = newSubTotal;

    if(newSubTotal < 1){
      if(confirm('There is No Outstanding Balance, Do you still want to proceed to add a new row? ')){

        //START ADD ANOTHER ROW
        self._addRowHelper(newSubTotal,'','','');
        //END ADD ANOTHER ROW
        return;

      }else{          
        return;
      }
    }

    //START ADD ANOTHER ROW
    self._addRowHelper(newSubTotal,'','','');
    //END ADD ANOTHER ROW
    return;

  },


removeRow: function(idx){

    self = this;
    if(self.maincartsection.splitpaymentformitems.items.length < 1){
      alert('List is Empty');
      return;
    }

    lastiteminarrayIndex = self.maincartsection.splitpaymentformitems.items.length-1;

      //REMOVE OTHER ITEMS BELOW TOP ITEM
      if(lastiteminarrayIndex == idx){
        self.maincartsection.splitpaymentformitems.items.splice(idx, 1); 

        if(self.maincartsection.splitpaymentformitems.items.length < 1){
          //self.splitPaymentClicked = false;
         // self.maincartsection.splitpaymentformitems.splitPaymentStatus = 0;
         // document.getElementById('customer_amount_paid').focus();  
           return;
         }


      }else{
        self.maincartsection.splitpaymentformitems.items = [];
       // self.splitPaymentClicked = false;
       // self.maincartsection.splitpaymentformitems.splitPaymentStatus = 0;
       // document.getElementById('customer_amount_paid').focus();
      }
      return;
      //END REMOVE OTHER ITEMS BELOW TOP ITEM

  },

0 个答案:

没有答案