Knockout.js: clear selection in select element

℡╲_俬逩灬. 提交于 2020-01-02 08:58:25

问题


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.


回答1:


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/




回答2:


Just add an 'optionsCaption', like this:

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

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



来源:https://stackoverflow.com/questions/11300258/knockout-js-clear-selection-in-select-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!