Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 687
sellmeadog Avatar asked Mar 04 '26 18:03

sellmeadog


2 Answers

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/

like image 191
RP Niemeyer Avatar answered Mar 06 '26 08:03

RP Niemeyer


Just add an 'optionsCaption', like this:

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

Updated fiddle: http://jsfiddle.net/Su8Zq/2/

like image 27
John Earles Avatar answered Mar 06 '26 08:03

John Earles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!