Knockoutjs (version 2.1.0): bind boolean value to select box

Gelin Luo picture Gelin Luo · May 9, 2012 · Viewed 9.7k times · Source

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: https://jsfiddle.net/greenlaw110/Ajm58/

Answer

RP Niemeyer picture RP Niemeyer · May 10, 2012

Here is an option that we explored for this one from this forum post:

ko.bindingHandlers.booleanValue = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        var observable = valueAccessor(),
            interceptor = ko.computed({
                read: function() {
                    return observable().toString();
                },
                write: function(newValue) {
                    observable(newValue === "true");
                }                   
            });
        
        ko.applyBindingsToNode(element, { value: interceptor });
    }
};

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: https://jsfiddle.net/rniemeyer/H4gpe/