Binding KnockoutJS to Radio Button with computed
http://stackoverflow.com/questions/10283580/binding-knockoutjs-to-radio-button-with-computed
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.debug.js"></script>
<div data-bind="text:name"></div>
<div data-bind="foreach:answers">
<label>
<span data-bind="text: name"></span>
<input type="radio" name="uniqueQuestionName" data-bind="click: $root.setCorrectAnswer,checked:$root.setCorrectAnswer.isRight" />
</label>
<br />
</div>
<hr/>
<pre data-bind="text: JSON.stringify(ko.toJS($root), null, 2)"></pre>
JavaScript
function Question() {
var self = this;
this.name = "My Question";
var i = 0;
this.answers = ko.observableArray([
new Answer(++i, "Answer 1", false),
new Answer(++i, "Answer 2", true),
new Answer(++i, "Answer 3", false)]);
this.setCorrectAnswer = function(correct) {
// alert(""+ this.correctAnswer().name())
console.log( correct.id())
if (correct !== self.correctAnswer()) {
ko.utils.arrayForEach(self.answers(), function(answer) {
answer.isRight(correct === answer);
});
self.correctAnswer(correct);
}
return true;
};
this.correctAnswer = ko.observable();
this.correctAnswer.subscribe(function(newValue) {
alert("The correct answer to " + this.name + " is now " + this.correctAnswer().name());
}, this);
}
function Answer(id, name, isRight) {
this.id = ko.observable(id);
this.name = ko.observable(name);
this.isRight = ko.observable(isRight);
}
ko.applyBindings(new Question());