Dan McElroy
Dan McElroy

Reputation: 426

Options value data-bind not working

I'm having an issue in mapping the elements of an object and binding them to an <option> element using Knockout.js.

The relevant section of HTML is as follows:

<!-- ko if: parentObjectExists -->
<!-- ko with: parentObject -->
<div class="form-group">
 <label class="control-label" for="subTaskDistributionInput">Distribution:</label>
 <select id="subTaskDistributionInput" data-bind="options: options.distributions,  optionsText: 'value', value: key" class="form-control input-sm"></select> 
</div>
<!-- /ko -->
<!-- /ko -->    

The elements of the options.distributions array contain two elements, key and value. Relevant Javascript:

function Options(data) {
  var self = this;
  self.distributions = ko.observableArray(data.Distributions);

  //Disposal
  self.isDisposed = false;
  self.dispose = function () {
      self.distributions.dispose();
      self.isDisposed = true;
  };
}

And the output options tags:

<option value>Average</option>
<option value>Triangular</option>

A Distribution contains two elements: key, an integer, and value, a String. The value element is definitely coming through accurately into optionsText, but the key attribute is not coming through into the HTML at all. I'm almost certain the issue here lies in the HTML. Alternative value: bindings that I've tried are 'key', function() { return key; }, $data.key and item.key, but none of these have worked. If anyone can see what I'm missing here, that would be greatly appreciated.

Upvotes: 0

Views: 648

Answers (2)

Muhammad Raheel
Muhammad Raheel

Reputation: 19882

You need to do it like this

<select id="subTaskDistributionInput" 
    data-bind="
        options: distributions,
        optionsText: $root.getValue,
        optionsValue: $root.getKey
    " 
class="form-control input-sm"></select>

Also see optionsValue instead of value

Fiddle Demo

See the Documentation

Upvotes: 2

Ijon Tichy
Ijon Tichy

Reputation: 456

I believe you should write

optionsValue: 'key'

Upvotes: 1

Related Questions