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

436 Views Asked by At

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.

3

There are 3 best solutions below

0
Daniel Conde Marin On BEST ANSWER

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>

0
Dani On

I tried out,

  data-bind:"value:name().nationality()[0].gender.Id" 

and the values got updated with each change in the options selected in the select control.

This worked out for me.

0
Dani On

Since JSON returned nationality as array object,

I have to bind it as,

 data-bind:"value:name().nationality()[0].gender.Id" 

 data-bind:"value:name().nationality()[1].gender.Id" 

 data-bind:"value:name().nationality()[2].gender.Id" 

and so on.

Hence worked out.