簡體   English   中英

根據數量和價格自動計算總數

[英]Calculate total automatically from quantity and price

使用knockout js制作Basic Web Application。

我有3文本框:

1.價格,2.數量,3.總計。

我想在用戶添加數量和價格數據時自動計算總計。

html代碼:

price:<input type="text" data-bind="value : itemPrice"><br/>
qty:<input type="text" data-bind="value : itemQTY"><br/>
total:<input type="text" data-bind="value : itemTotal">

敲除js代碼:

ViewModel = function() {
       var self = this;        
       self.itemPrice = ko.observable();
       self.itemQTY = ko.observable();
       self.itemTotal = ko.observable();
};

建議非常感激。

使用ko.computed

self.itemTotal = ko.computed(function() {
   return self.itemPrice()*self.itemQTY();
});

使用ko.computed

self.itemTotal = ko.computed(function(){
  if(isNaN(self.itemPrice()) == true && isNaN(self.itemQTY()) == true || isNaN(self.itemQTY()) == true || isNaN(self.itemPrice()) == true){
        return '0.00';
  }else{
        return  self.itemPrice()*self.itemQTY();
  }
});

上述條件將檢查用戶是否輸入了text data ,如果用戶輸入了文本數據,它將自動設置為0.00否則將根據input計算total ,然后顯示在總數textbox

&將總文本框readonly以便用戶無法對其進行編輯。 喜歡 :

<input type="text" data-bind="value : itemTotal" readonly>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM