Boy Pasmo
Boy Pasmo

Reputation: 8501

how do you set a value that is an observable in a dropdown?

var vm = (function() {
      var selectedFoo = ko.observable(),
          foos = [
            { id: 1, fooName: 'fooName1', fooType: 'fooType1' },
            { id: 2, fooName: 'fooName2', fooType: 'fooType2' },
            { id: 3, fooName: 'fooName3', fooType: 'fooType3' },
          ];
    
      return {
        selectedFoo: selectedFoo,
        foos: foos
      };
    }());
            
            ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options: foos, 
                   optionsText: 'fooName', 
                   optionsCaption: 'Select foo', 
                   value: selectedFoo"></select><br />
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>

While above code works, how would set the initial value of the dropdown? Say you got an id value of 2 from an ajax call. How would you set the selected option based on the id?

I've looked in the for solutions but I only found adding a optionsValue but I need the member of the selected option as display

Any help would be much appreciated.

Upvotes: 0

Views: 148

Answers (1)

JotaBe
JotaBe

Reputation: 39045

You're misundertanding something. I've added the selected value in your snippet, and, if you change the id, the select list is updated correcty, and you still display what you want. I've added a bound textbox where you can type the id so that you can check it works as expected.

NOTE: just in case the comment below is what I couldn't understand from your question, I'm implementing a new writable computed observable that allos to use the whole object as selection.

var vm = (function() {
      var foos = [
            { id: 1, fooName: 'fooName1', fooType: 'fooType1' },
            { id: 2, fooName: 'fooName2', fooType: 'fooType2' },
            { id: 3, fooName: 'fooName3', fooType: 'fooType3' },
          ],
          selectedFoo = ko.observable(),
          selectedFooId = ko.computed({
            read: function() {
              return selectedFoo() ? selectedFoo().id : null;
              },
            write: function(value) {
              var newSel = foos.find(function(f) {return f.id == value;});
              selectedFoo(newSel);
              }
          });
    
      return {
        selectedFooId: selectedFooId,
        selectedFoo: selectedFoo,
        foos: foos
      };
    }());
            
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options: foos, 
                   optionsText: 'fooName', 
                   optionsCaption: 'Select foo', 
                   value: selectedFoo"></select><br />
<input type=text data-bind="value: selectedFooId, valueUpdate:'keyup'" />
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>

Upvotes: 4

Related Questions