KnockoutJS radio buttons not changing like checkboxes do
- by Gaui
I have the same data structure for checkboxes and radio buttons. When checking the checkboxes, they return correct boolean value ('chosen' variable).
However, when I check the radio buttons, 'chosen' always changes to the 'value' (integer).
Also the radio buttons don't get "checked" in the beginning, even though 'chosen' == true
Javascript:
function attributeValueViewModel(data) {
var self = this;
self.id = ko.observable(data.id);
self.attributeID = ko.observable(data.attributeID);
self.value = ko.observable(data.value);
self.chosen = ko.observable(data.chosen);
}
function viewModel() {
var self = this;
self.attributeValues1 = ko.observableArray([]);
self.attributeValues2 = ko.observableArray([]);
self.addToList = function(data) {
ko.utils.arrayForEach(data, function(item) {
self.attributeValues1.push(new attributeValueViewModel(item));
self.attributeValues2.push(new attributeValueViewModel(item));
});
};
}
var arr = [
{
"id": 55,
"attributeID": 28,
"value": "Yes",
"chosen": false,
},
{
"id": 56,
"attributeID": 28,
"value": "No",
"chosen": true,
},
{
"id": 62,
"attributeID": 28,
"value": "Maybe",
"chosen": false,
}
];
var vm = new viewModel();
ko.applyBindings(vm);
vm.addToList(arr);
HTML
<b>Checkbox:</b>
<div id="test1">
<span data-bind="foreach: attributeValues1()">
<input type="checkbox" data-bind="value: id(), checked: chosen, attr: { name: 'test1' }" />
<span data-bind="text: value()"></span>
<span data-bind="text: chosen()"></span>
</span>
</div>
<br />
<b>Radio:</b>
<div id="test2">
<span data-bind="foreach: attributeValues2()">
<input type="radio" data-bind="value: id(), checked: chosen, attr: { name: 'test2' }" />
<span data-bind="text: value()"></span>
<span data-bind="text: chosen()"></span>
</span>
</div>?
Here is my fiddle: http://jsfiddle.net/SN7Vn/1/
Can you please explain this behavior and why the radio buttons don't update boolean (like checkboxes do)?