title: Knockout: How can I set the value of a select box whose options are javascript objects?
body: <p>I have a <code>select</code> element that is bound to a list of complex javascript objects using the <code>options</code> binding:</p>
  
  <pre><code>&lt;select data-bind="options: availableCountries, optionsText: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'"&gt;&lt;/select&gt;
  </code></pre>
  
  <p>where availableCountries is an observable array of javascript objects. You can see the full example <a href="http://jsfiddle.net/7csj5/1/" rel="nofollow noreferrer">in this fiddle</a>.</p>
  
  <p>Now, this works fine when I select an item in the list. However, if I need to update the value from some other part of the application, I will only be able to do so if I use the exact same Country object as lies in the availableCountries array. This has also been established in this <a href="https://stackoverflow.com/questions/11638609/manually-set-default-values-for-a-select-box-using-knockout-on-complex-objects">related question</a>, but unfortunately it does not solve my problems.</p>
  
  <p>In the documentation of the <a href="http://knockoutjs.com/documentation/options-binding.html" rel="nofollow noreferrer">options binding</a>, they anticipate this problem, and say that I should use the <code>optionsValue</code> binding:</p>
  
  <blockquote>
    <p>Typically you’d only want to use optionsValue as a way of ensuring
    that KO can correctly retain selection when you update the set of
    available options. For example, if you’re repeatedly getting a list of
    “car” objects via Ajax calls and want to ensure that the selected car
    is preserved, you might need to set optionsValue to "carId" or
    whatever unique identifier each “car” object has, otherwise KO won’t
    necessarily know which of the previous “car” objects corresponds to
    which of the new ones.</p>
  </blockquote>
  
  <p>But this unfortunately will not work, as it also affects the value binding - if I set <code>optionsValue</code> to <code>'countryName'</code>, <code>selectedCountry</code> will only contain the name of the country and not the entire object.</p>
  
  <p>I'm looking for a way to combine these. I still want value to be the entire object, but I want the option value comparison to use a specific property that I specify. Basically, something in the lines of:</p>
  
  <pre><code>&lt;select data-bind="options: availableCountries, optionsText: 'countryName', optionsComparator: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'"&gt;&lt;/select&gt;
  </code></pre>
  
  <p>However, as far as I can see, this involves modifying the <code>value</code> binding. Do I have any other options? Can I solve this in some other way? Extenders? A custom binding handler?</p>