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?
Asked
Active
Viewed 860 times
1 Answers
1
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);
};

RP Niemeyer
- 114,592
- 18
- 291
- 211
-
my real goal is to have an empty value for all the select box options except some that should prompt the user to enter a value manually and then set it. If the user select back an option that should have the empty string as input value knockout should set the string empty – Stefano Nov 20 '12 at 21:46
-
Something like this: http://jsfiddle.net/rniemeyer/ELywY/ or do the options have actual values that go with them and some you can override? – RP Niemeyer Nov 21 '12 at 03:36
-
using the subscriber I've solved my problem. Your solution works, thank you – Stefano Nov 21 '12 at 13:44