Question

I have an input field that should be populated dynamically when a selectbox changes it's value. So, I binded the variable to the input and another value to the selectbox's selected value. Now I want to be able to change the input value programmatically: for certains values of the selectbox the value should be an empty string and for others I should set it with some javascript code when the user does some actions. I though to use a computed function, so I can return the empty string but this lead me to a problem: how can I then set the value programmatically when the other selectbox options are selected?

Was it helpful?

Solution

If your goal is to default in a value into the input whenever the select changes and allow a user to update it freely, then a good choice is to use a manual subscription.

var ViewModel = function() {
   this.selectedValue = ko.observable();
   this.otherValue = ko.observable();

   this.selectedValue.subscribe(function(newValue) {
       //perform whatever logic that you need to determine how the other value should be populated based on the dropdown's current value (newValue)
       this.otherValue(calculatedValue);
   }, this);
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top