1

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);
0

2 Answers 2

2

Here is the fiddle : http://jsfiddle.net/whx96806/1/

Please try this snippet and see if it helps :

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

};

ko.applyBindings(ViewModel);
1
  • Your snippet works, but problem with my code was that i didn't use this keyword when declaring variables, thx.
    – datalore
    Nov 2, 2015 at 12:38
0

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/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.