title: Knockout.js - Reload a dropdown with new options using the value of another drop down
body: <p>I've seen similar things, where people have wanted to do this in ASP .NET, generic JavaScript, PHP, etc., but now here we have KnockOut that throws a wrench in things, since its fields are already rendered dynamically.  Now here I go wanting to rewrite a dropdown when another is changed... dynamic loading on top of dynamic loading, all in old-fashioned cascading style....</p>
  
  <p>I have a dropdown, "ourTypes", I've called it, that when changed, should re-write the options of the "slots" dropdown to its left.  I have a <code>.subscribe()</code> function that creates new options based on a limit I get from the "ourTypes" value.  All well and good, but how do we make the dropdown actually reflect those new values?</p>
  
  <p><strong>HTML:</strong></p>
  
  <pre><code>&lt;select data-bind="options: $root.slots, optionsValue: 'Value', optionsText: 'Text', value: $data.SlotPosition"&gt;&lt;/select&gt; 
  &lt;select data-bind="options: $root.ourTypes, optionsValue: 'ID', optionsText: 'Name', value: $data.OurTypeId"&gt;&lt;/select&gt;
  </code></pre>
  
  <p><strong>JavaScript:</strong></p>
  
  <pre><code>var slots = [
      { Text: "1", Value: "1" },
      { Text: "2", Value: "2" },
      { Text: "3", Value: "3" }
  ];
  var ourTypes = [
      { ID:"1", Name:"None", Limit:0 },
      { ID:"2", Name:"Fruits", Limit:5 },
      { ID:"3", Name:"Vegetables", Limit:5 },
      { ID:"4", Name:"Meats", Limit:2 }
  ];
  var dataList = [        
      { SlotPosition: "1", OurTypeId: 4 },
      { SlotPosition: "2", OurTypeId: 2 },
      { SlotPosition: "3", OurTypeId: 3 }
  ];
  
  var myViewModel = new MyViewModel(dataList);
  ko.applyBindings(myViewModel);
  
  function MyViewModel(dataList) {
      var self = this;
      self.slots = slots;
      self.ourTypes = ourTypes;
      self.OurTypeId = ko.observable(dataList.OurTypeId);
      self.SlotPosition = ko.observable(dataList.SlotPosition);
  
      self.OurTypeId.subscribe(function() {
          if (!ko.isObservable(self.SlotPosition))
              self.SlotPosition = ko.observable("1");
  
          // Get our new limit based on value
          var limit = ko.utils.arrayFirst(ourTypes, function(type) {
              return type.ID == self.OurTypeId();
          }).Limit;  
  
          // Build options here
          self.slots.length = 0;
          self.slots.push({Text:"",Value:""});
          for (var i=1; i &lt; limit+1; i++) {
              self.slots.push({Text:i, Value:i});
          }
  
          // What else do I do here to make the dropdown refresh
          // with the new values?
      });
  }
  </code></pre>
  
  <p>Fiddle:  <a href="http://jsfiddle.net/navyjax2/Lspwc4n4/" rel="nofollow">http://jsfiddle.net/navyjax2/Lspwc4n4/</a></p>