Binding true / false to radio buttons in Knockout JS
http://stackoverflow.com/questions/10127001/binding-true-false-to-radio-buttons-in-knockout-js
by kougiland
HTML
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<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>
<hr/>
<div data-bind="text: ko.toJSON($root)"></div>
CSS
li { margin: 5px; background: #eee; height: 50px; }
.menu { position: absolute; background-color: #000; color: #fff; height: 100px; }
JavaScript
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
});
};
ko.applyBindings(new ViewModel());