Dani
Dani

Reputation: 700

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

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.

Upvotes: 0

Views: 399

Answers (3)

Dani
Dani

Reputation: 700

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.

Upvotes: 1

Dani
Dani

Reputation: 700

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.

Upvotes: 1

Daniel Conde Marin
Daniel Conde Marin

Reputation: 7742

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>

Upvotes: 0

Related Questions