0

can anyone help me activate the first radio button as standard

here is my code

<div>Wiederholung</div>
<div data-bind="foreach:answers">
        <label>
            <input type="radio" name="wiederholung" data-bind="click: $root.setChosenAnswer" />
            <span data-bind="text: name"></span>
        </label>
        <br />
</div>
<pre data-bind="text: JSON.stringify(ko.toJS($root), null, 2)"></pre>

js:

function Question() {
    var self = this;
    this.answers = ko.observableArray([
        new Answer("Nie", true),
        new Answer("Täglich", false),
        new Answer("Wöchentlich", false)]);

    this.setChosenAnswer = function(wahl) {
        if (wahl !== self.userAnswer()) {
            ko.utils.arrayForEach(self.answers(), function(answer)  {
                answer.isChosen(wahl === answer); 
            });

            self.userAnswer(wahl);           
        }
        return true;
    };

    this.userAnswer = ko.observable();

    this.userAnswer.subscribe(function(newValue) {
        alert("Ich moechte mein Termin " + this.userAnswer().name() + " Wiederholen");
    }, this);
}

function Answer(name, isChosen) {
    this.name = ko.observable(name);
    this.isChosen = ko.observable(isChosen);
}

ko.applyBindings(new Question());

demo

Taylan Aydinli
  • 4,333
  • 15
  • 39
  • 33
Gildas.Tambo
  • 22,173
  • 7
  • 50
  • 78

3 Answers3

1

You may use $index() function to determine index of the item in the array as following:

<input type="radio" name="wiederholung" data-bind="click: $root.setChosenAnswer, attr: {checked: $index()==0 }" />

But it works with knockout 2.1 and above while in your demo you are using 2.0.

Pavel Kutakov
  • 971
  • 1
  • 7
  • 11
1

Try this in html

<input type="radio" name="wiederholung" data-bind="value: $data.name, checked: $root.defaultChecked, click: $root.setChosenAnswer" />

in js

this.defaultChecked = "Nie";

hawk
  • 5,409
  • 2
  • 23
  • 29
0

From "checked" binding 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 or the value specified by the checkedValue parameter.

So you need to:

  1. Change your radio element markup to include value="true" because you want it to be selected if you got true.
  2. Change your setChosenAnswer function to return string values either "true" or "false".

You may also check this SO question for radio binding in KnockoutJS

Community
  • 1
  • 1
ebram khalil
  • 8,252
  • 7
  • 42
  • 60