user2653444
user2653444

Reputation:

how to bind data to dropdown dynamically using knockout.js?

I am new to knockout.js. I wasn't able to bind data from api to dropdown using knock out js.

My Json data from api and dropdown is:

[{
ContactID: 0,
FirstName: "Aaa",
LastName: "bbb",
MobileNumber: null,
StartDate: "0001-01-01T00:00:00",
EndDate: "0001-01-01T00:00:00"
},
{
ContactID: 0,
FirstName: "Ccc",
LastName: "ddd",
MobileNumber: null,
StartDate: "0001-01-01T00:00:00",
EndDate: "0001-01-01T00:00:00"
}
]
<select id="selectmenu1" name="" data-theme="c" data-bind="optionsCaption: 'Choose...'">        </select> 

I just to bind firstname,lastname,contactID to dropdown and display firstname and lastname as text and contactID is the value field for that item. Could anyone please give some suggestions regarding this?

Upvotes: 5

Views: 19580

Answers (2)

Pylyp Lebediev
Pylyp Lebediev

Reputation: 2121

You can use knockout mapping plugin. More details is here

And also you can look at great tutorial about how to load and save data

Upvotes: 0

nemesv
nemesv

Reputation: 139748

You need to use the options binding, where you need to specify:

  • your array of items in the options (see in doc Example 3)
  • you need to set the optionsValue: 'ContactID' to have the ContactID as the value
  • you need to specify a function in the optionsText which builds your select texts (see in doc Example 4)

So your final binding will look like:

<select id="selectmenu1" name="" data-theme="c" 
  data-bind="options: contacts, 
             optionsValue: 'ContactID', 
             optionsText: function(i) { return i.FirstName + ' ' + i.LastName }, 
             optionsCaption: 'Choose...'">        
</select>

Demo JSFiddle.

Upvotes: 12

Related Questions