knockout.js - Accessing knockout js selected option inside a computed variable -
i want create computed observable return percentage value:
self.percentage = ko.computed(function(){ var percentage = (self.amount() * self.selecteditem().itemvat)/100; return percentage; });
i keep getting - uncaught typeerror: cannot read property 'itemvat' of undefined.
var items = function(item_name, item_number, item_vat) { this.itemname = item_name; this.itemnumber = item_number; this.itemvat = item_vat; };
an ajax call used create new items , assign them select box using options binding following:
this.availableitems = ko.observablearray(); this.selecteditem = ko.observable(); jquery.each(data, function(i, val) { self.availableitems .push(new items(val.item_name,val.item_number,val.item_vat)); }); <select class="form-control" name="item_name" id="item_name" data-bind = "options: availableitems, optionstext: 'itemname', value: selecteditem, optionscaption: 'choose...'"></select>
by specifying optionscaption
, allow selecteditem
undefined. test that, , you're ok.
self.percentage = ko.computed(function() { if (self.selecteditem() === undefined) return 0; var percentage = (self.amount() * self.selecteditem().itemvat) / 100; return percentage; });
Comments
Post a Comment