2013-03-18 10 views
18

Sto tentando di utilizzare knockout.js per popolare e gestire una casella <select/>. Mi piacerebbe che il valore iniziale fosse vuoto.knockout.js - impostazione di una selezione vuota

Tuttavia, sto riscontrando problemi nel tentativo di forzare il valore gestito a essere nullo in qualsiasi momento, figuriamoci inizialmente.

Ad esempio, si consideri this fiddle:

HTML:

<select data-bind="options: myOptions, value: myValue"></select> aka 
<span data-bind="text: myValue"></span> 

<div> 
    <button data-bind="click: setMyValue(null)">clear the selection</button> 
    <button data-bind="click: setMyValue('one')">select "one"</button> 
    <button data-bind="click: setMyValue('four')">select "four"</button> 
</div> 
<ul data-bind="foreach: log"> 
    <li>message: <span data-bind="text: message"></span></li> 
</ul> 

JS:

function Model() { 
    var self = this; 
    self.myOptions = ['one', 'two', 'three', 'four']; 
    self.myValue = ko.observable(); 
    self.setMyValue = function (val) { 
     return function(){ 
      this.log.push({ 
       message: "ok, trying to set value as " + val 
      }); 
      self.myValue(val); 
     }; 
    }; 
    self.log = ko.observableArray([]); 
} 
var model = new Model(); 
ko.applyBindings(model); 

I pulsanti select "one" e select "four" lavorano per cambiare la selezione forzando un aggiornamento myValue(). Tuttavia, deselezionare il pulsante di selezione non funziona. La selezione non viene cancellata da myValue(null), which is what I thought was the proper way to do it.

Cosa sto sbagliando?

risposta

31

È necessario il set di rilegatura optionsCaption.

<select data-bind="options: myOptions, value: myValue, optionsCaption: 'select...'"></select> 

Updated Fiddle

Problemi correlati