Making Basic Web Application using knockout js
.
I have 3
textboxes:
1. price, 2. quantity, 3. total.
I want to calculate total automatically when user add data in quantity & in price.
html code :
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">
knockout js code :
ViewModel = function() {
var self = this;
self.itemPrice = ko.observable();
self.itemQTY = ko.observable();
self.itemTotal = ko.observable();
};
Suggestion are greatly appreciated.
Use ko.computed
self.itemTotal = ko.computed(function() {
return self.itemPrice()*self.itemQTY();
});
Use 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();
}
});
above condition will check that if user has entered text data
, if user has entered text data then it ll automatically set to 0.00
otherwise calculate total
on base of input
then show in total textbox
.
& make total textbox readonly
so user can't edit it. Like :
<input type="text" data-bind="value : itemTotal" readonly>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.