This is my first post here after trying to google an answer. If this had been answered somewhere before then if you could help directing me to right place that would be great.
I am trying to figure out a way to do 2 way binding between 2 fields.
I have a 2 fields on my form that do weight calculation. If you enter weight in pounds into field #1 then Knockout will calculate the weight in kilograms into field #2. I have no problem with this one and here is my jsfiddle for this http://jsfiddle.net/ubiquitous_tom/tVh3g/
var weight = 180;
self.weight = ko.observable(weight.toFixed(2));
self.weightKG = ko.computed(function(){
var kg_weight = parseFloat(self.weight())/2.2;
return !isNaN(kg_weight) ? kg_weight.toFixed(2) : undefined;
});
Now the problem I have is that when I'm trying to put weight in kilograms into field #2. It should calculate the weight in pounds into field #1 but it doesn't do it. I have no idea how to make it work because all the code that i try using computed "read" and "write" on both fields give me infinite loop error so I think I'm just not doing something right.
If anyone can help me out that would be great. I'm sure this is something super simple but I am totally new to Knockout and I am not quite sure how to make it work right. here's the jsfiddle for the one i'm trying to work on http://jsfiddle.net/ubiquitous_tom/VmZLZ/
var weight = 180;
self.weight = ko.observable(weight.toFixed(2));
self.weightKG = ko.computed({
read: function() {
return parseFloat(self.weight().toFixed(2));
},
write: function(newValue) {
var kg_weight = parseFloat(newValue)/2.2;
return !isNaN(kg_weight) ? kg_weight.toFixed(2) : undefined;
}
});