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);
Jesus Angulo
  • 2,646
  • 22
  • 28
datalore
  • 317
  • 1
  • 14

2 Answers2

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);
Ash
  • 2,575
  • 2
  • 19
  • 27
  • Your snippet works, but problem with my code was that i didn't use this keyword when declaring variables, thx. – datalore Nov 02 '15 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/

datalore
  • 317
  • 1
  • 14