Search code examples
knockout.jsknockout-3.2

KnockoutJS checked binding with radio button


I have a list of objects that I loop through and create radio button for them, then I would like to store the object that is selected in an observable, but I cant figure out how to do this. This fiddle is example of something that im trying to do: jsfiddle.net/whx96806/ , but it doesn't work.

 <div data-bind="foreach: items">
<input type="radio" name="test" data-bind="checkedValue: $data, checked: $root.chosenItem" />
<span data-bind="text: itemName"></span>
</div>
<div><p>You have selected: <span data-bind="text:JSON.stringify(chosenItem())"></span></p></div>
<button data-bind="click:print">Print</button>

And the js code:

function ViewModel () {
    items= ko.observableArray([
    { itemName: 'Choice 1' },
    { itemName: 'Choice 2' }
    ]);
    chosenItem= ko.observable();

    print = function () { alert(chosenItem()); };

};

var vm = new ViewModel();
ko.applyBindings(vm);

Solution

  • Problem was I forgot to use 'this' in my view model, this should work:

    function ViewModel () {
        this.items= ko.observableArray([
        { itemName: 'Choice 1' },
        { itemName: 'Choice 2' }
        ]);
        this.chosenItem= ko.observable();
    
        print = function () { alert(chosenItem()); };
    
    };
    
    var vm = new ViewModel();
    ko.applyBindings(vm);
    

    Heres the fiddle: http://jsfiddle.net/whx96806/2/