Radio buttons Knockoutjs

NoviceDeveloper picture NoviceDeveloper · Apr 28, 2013 · Viewed 44.7k times · Source

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.

Answer

nemesv picture nemesv · Apr 28, 2013

The checked binding works differently for radio buttons and checkboxes:

From the documentation:

For radio buttons, KO will set the element to be checked if and only if the parameter value equals the radio button node’s value attribute. So, your parameter value should be a string.

So you need to set the value attribute of your inputs to "A" and "B" and then bind to the radioSelectedOptionValue which will contain "A" or "B" depending on which options is selected:

<label>
    <input name="Test" type="radio" value="A" 
             data-bind="checked: radioSelectedOptionValue" />
    Alpha
</label>
<label>
    <input name="Test" type="radio" value="B" 
             data-bind="checked: radioSelectedOptionValue" />
    Beta
</label>

If you want to keep your boolean properties: A and B, you need to make them ko.computed (read-only, writable) which will use/convert the value of the radioSelectedOptionValue:

this.radioSelectedOptionValue = ko.observable();
this.A = ko.computed( {
        read: function() {
            return this.radioSelectedOptionValue() == "A";
        },
        write: function(value) {
            if (value)
                this.radioSelectedOptionValue("A");
        }
    }, this);

Demo JSFiddle.