Search code examples
javascriptknockout.jsknockout-mapping-pluginknockout-2.0

Binding true / false to radio buttons in Knockout JS


In my view model I have a IsMale value that has the value true or false.

In my UI I wish to bind it to the following radio buttons:

<label>Male
   <input type="radio" name="IsMale" value="true" data-bind="checked:IsMale"/>
</label> 
<label>Female
   <input type="radio" name="IsMale" value="false" data-bind="checked:IsMale"/>
</label>

The problem I think is checked expects a string "true" / "false". So my question is, how can I get this 2-way binding w/ this UI and model?


Solution

  • One option is to use a writeable computed observable.

    In this case, I think that a nice option is to make the writeable computed observable a "sub-observable" of your IsMale observable. Your view model would look like:

    var ViewModel = function() {
       this.IsMale = ko.observable(true);
    
       this.IsMale.ForEditing = ko.computed({
            read: function() {
                return this.IsMale().toString();  
            },
            write: function(newValue) {
                 this.IsMale(newValue === "true");
            },
            owner: this        
        });          
    };
    

    You would bind it in your UI like:

    <label>Male
       <input type="radio" name="IsMale" value="true" data-bind="checked:IsMale.ForEditing"/>
    </label> 
    <label>Female
       <input type="radio" name="IsMale" value="false" data-bind="checked:IsMale.ForEditing"/>
    </label>
    

    Sample: http://jsfiddle.net/rniemeyer/Pjdse/