Knock out js - Link values ​​based on the option selected in the select control

advertisements

I'm working with knock out js

I'm binding the values of the control as follows,

Html,

<html>
    <select id ="eg" data-bind:"value:name().nationality.gender.Id"/>
        <option>1</option>
        <option>2</option>
        <options>3</option>
        <option>4</option>
    </select>
</html>

JavaScipt,

function viewmodel(objservermodel)
{
    var self = this;
    self.name = ko.observable(ko.mapping.fromJS($.parseJSON(objservermodel));
}

json comes like this,

   {"nationality":[{"gender":{"Id":"1"}}]}

but when i refer to it as "data-bind:"value:name().nationality.gender.Id""

it says Id is undefined,

I also tried,

   "value: name().nationality[0].gender.Id" or "value: name().nationality()[0].gender().Id"

I only got console error message as,

     Uncaught Error: Unable to parse bindings.
     gender undefined
     Bindings value:  value:value: name().nationality[0].gender.Id

Could someone tell me how to exactly bind to Id,

Id value should be binded based on the option selected in the select control.

I tried several, still didn't arrive at the solution,

Any help is greatly appreciated,

Thanks.


A single select list binds to an observable array like this:

Javascript:

function viewmodel(objservermodel)
{
    var parseJson = function(){
        ......//parse nationalities json array
    }

    self.nationalities = ko.observableArray(parseJson()); //js array with all parsed nationalities from incoming json
    self.selectedNationality = ko.observable(); //this gives you the current selected nationality object

}

ko.applyBindings($("#foo")[0], viewmodel); //apply bindings!!!

HTML:

<div id="foo">
<select id ="eg" data-bind:"options: nationalities, value: selectedNationality"/>
</div>