Reputation: 803
I have not used Knockout in a while and am running into an issue when trying to trim the input value of a form field to two decimal places. I created the below computed observable and am subscribing to it by the observable that I want to update with the trimmed value. Can anyone tell me what I am doing wrong?
View Model
function createViewModel() {
var self = {};
self.SalesRepId = ko.observable().extend({ required: true });
self.PriceAdvanced = ko.observable("").extend({ required: true, min: 1, max: 200 });
self.decimalValue = ko.computed(function () {
var num = self.PriceAdvanced().slice(0, (self.PriceAdvanced().indexOf(".")) + 3);
return num;
}).extend({ notify: "always" });
self.PriceAdvanced.subscribe(self.decimalValue);
return self;
}
HTML:
<div class="form-group col-xs-12">
<label class="label-col col-xs-4 control-label labelFormat" for="PriceAdvanced"><span class="warn">* </span>Advanced Criminal History Search</label>
<div class="col-xs-8">
<input class="form-control max225" type="text" id="PriceAdvanced" name="PriceAdvanced" data-bind="textInput: PriceAdvanced" size="23" placeholder="$0.00" />
</div>
</div>
Upvotes: 1
Views: 1032
Reputation: 3959
ko.applyBindings
method? If not, you need to call that at the end of your code.decimalValue
to limit the decimal places to 2, and then PriceAdvanced
would subscribe to the updated value of decimalValue
, right? But subscribe doesn't work like that. Computed observables listen to the observables inside them, and .subscribe
functions are listeners to the observable itself. So your code would have been in a never-ending loop.Also I think you only wanted to limit decimal places, not the number of digits itself right? So I changed the code to trim the value only if a decimal point exists.
function createViewModel() {
var self = {};
self.SalesRepId = ko.observable().extend({ required: true });
self.PriceAdvanced = ko.observable("").extend({ required: true, min: 1, max: 200 });
self.decimalValue = ko.computed(function () {
var num = self.PriceAdvanced().indexOf(".") > -1? self.PriceAdvanced().slice(0, (self.PriceAdvanced().indexOf(".")+3)): self.PriceAdvanced();
//return num;
self.PriceAdvanced(num);
}).extend({ notify: "always" });
return self;
}
ko.applyBindings(new createViewModel());
Note: Your extenders min: 1
, max: 200
will not work as PriceAdvanced
holds a string rather than a number.
Upvotes: 2