Search code examples
javascriptknockout.jsknockout-2.0ko.observablearray

Knockout.js: clear selection in select element


I need to clear the selection from a <select> element. I've already read such posts as Knockoutjs clear selected value in combobox and have tried the accepted answers, but those solutions don't seem to be working (don't know if something has changed in Knockout 2 since the answer was accepted?).

Here's an example view model:

var ClearSelectionViewModel = function () {
    var self = this;

    self.station = ko.observable();

    self.selectedStation = ko.observable();
    self.selectedStation.subscribe(function (value) {
        self.station(value);
    });

    self.stations = ko.observableArray(['CLT', 'PHL', 'PHX', 'PIT']);

    self.clearSelectedStation = function () {
        self.selectedStation(null);
    };
};

ko.applyBindings(new ClearSelectionViewModel());​

When the clearSelectedStation is invoked, the bound view model property should be set to null and this should be reflected in the UI by the bound <select> element appearing blank and expanding the list of options revealing no highlighted items. However, what I'm noticing is that if you try to set the bound value property (selectedStation) to anything not in the array of options (stations), the binding seems to be ignored.

This fiddle illustrates what I'm talking about: http://jsfiddle.net/sellmeadog/Su8Zq/1/

I don't want to "pollute" the options array with a blank value if I don't have to. I would like to know how to get the solution in the linked post to work.


Solution

  • One option would be to use the optionsCaption additional binding for the "not selected" value. It has to be set to something for it to be used, but you could set it to " ".

    <select data-bind="optionsCaption: ' ', options: stations, value: selectedStation"></select>
    

    Sample: http://jsfiddle.net/rniemeyer/Su8Zq/3/