I want to bind boolean value to select element using KO v2.1.0, but obviously it doesn't work as expected.
html code:
<select data-bind="value: state">
<option value="true">On</option>
<option value="false">Off</option>
</select>
Javascript code:
var model = {
state: ko.observable(false)
};
ko.applyBindings(model)
So I expect the select box goes to "Off" position with the initial value false
but it was at "On". If I put state: ko.observable("false")
it will be correct but that's not I wanted. Anyone know how to bind the boolean value to select box with KO?
Jsfiddle: http://jsfiddle.net/greenlaw110/Ajm58/
Here is an option that we explored for this one from this forum post:
So, we use a custom binding to inject a writeable computed observable between the UI and our view model. This is just an alternative to doing it directly in your view model.
Sample here: http://jsfiddle.net/rniemeyer/H4gpe/
This happens because the select is working with strings, and not booleans at any stage. You should try a ko.computed( ... ) value instead.
Check here for details: http://jsfiddle.net/Ajm58/3/
Much easier than the other answers: use the
options
-Binding.The answer is in the kind of lengthy expression below:
By using the options binding, you're able to assign virtually everything to the value of an option. It's rather uncommon, I guess, to bind an explicit value to the options binding, but in this 2-way case, it is reasonable.
I think I got the answer, put the number "1" and "0" to the option value respectively:
See http://jsfiddle.net/greenlaw110/Ajm58/2/