Ctrl_Alt_Defeat
Ctrl_Alt_Defeat

Reputation: 4009

Bind to dropdown with knockout?

I have a list of statuses which are returned from an ajax call to a Ref Data service

I have this defined in my js file:

self.StatusIdList = ko.observableArray();
self.StatusTextList = ko.observableArray();

This is the success handler of my ajax call:

success: function (data, textStatus, message) {
    $.each(data, function (index, item) {
        self.StatusTextList.push(item.statusDescription);
        self.StatusIdList.push(item.statusId);
    });
},

This is what I have in my HTML

<select data-bind="options: StatusIdList, value: currentFormStatus, optionsText: StatusTextList" class="span12"></select>

If I set the options to StatusTextList then the dropdown is populated with the list of statuses as expected - however with it set to ID it is populated with the list of ids which I don't want.

So I attempted to use optionsText and was hoping it would then display the Name in the dropdown but keep the unique id per status at the option value but in the dropdown with my current code as above it is displaying as below:

<option value="1">[object Window]</option>

Where actually the unique id of statusId = 1 should be displayed as 'Order Received'

Upvotes: 0

Views: 67

Answers (1)

adiga
adiga

Reputation: 35202

You don't need 2 separate arrays for populating the dropdown. Create an observableArray called StatusList with items which have both statusId and statusDescription properties. (more on options binding from KO website)

In your HTML:

<select data-bind="options: StatusList, value: currentFormStatus, optionsText: 'statusDescription', optionsValue: 'statusId', optionsCaption: 'Select'"></select>

The optionsText should point to whatever property in array, you want displayed as text in the dropdown. In our case it is statusDescription.

The optionsValue should point to the property which is value for the option. In this case it is statusId.

var viewModel = function (data) {
   var self = this;
   self.currentFormStatus = ko.observable();
   self.StatusList = ko.observableArray([]);

   // functions, ajax etc 
};

In your success callback:

// you can push to the array in your callback like this
// each item in "data" should have "statusDescription" and "statusId" properties
success: function (data, textStatus, message) {
    $.each(data, function (index, item) {
       self.StatusList.push(item);
    });
},

I have created a fiddle

Upvotes: 2

Related Questions