I have 2 values that I get from server A and B. I can only have one true at a time.
Again what I need is one of the radios to be checked at a time so one true value only.
var viewModel = {
radioSelectedOptionValue: ko.observable("false"),
A: ko.observable("false"),
B: ko.observable("false")
};
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js"></script>
<div class='liveExample'>
<h3>Radio View model</h3>
<table>
<tr>
<td class="label">Radio buttons:</td>
<td>
<label><input name="Test" type="radio" value="True" data-bind="checked: A" />Alpha</label>
<label><input name="Test" type="radio" value="True" data-bind="checked: B" />Beta</label>
</td>
</tr>
</table>
A-<span data-bind="text: A"></span>
B-<span data-bind="text: B"></span>
</div>
Knockout 3.x added the checkedValue binding option. This allows you to specify values other than strings.
http://jsfiddle.net/t73d435v/
The
checked
binding works differently for radio buttons and checkboxes:From the documentation:
So you need to set the
value
attribute of your inputs to "A" and "B" and then bind to theradioSelectedOptionValue
which will contain "A" or "B" depending on which options is selected:If you want to keep your boolean properties:
A
andB
, you need to make themko.computed
(read-only, writable) which will use/convert the value of theradioSelectedOptionValue
:Demo JSFiddle.