Knockoutjs清除下拉框中的选定值

4
我有一个简单的knockout.js应用程序:
视图:
<select data-bind="options: allDocumentTypes , optionsCaption: 'Choose ...', optionsValue: 'id', optionsText: 'name', selectedOptions: selectedDocument"></select>
<span data-bind="click: cl">CLEAR VALUE!</span>

这个简单的ViewModel:
function documentType(id, name){
    this.id = id;
    this.name = name;
}

var viewModel = {
    allDocumentTypes: ko.observableArray([]),
    selectedDocument: ko.observable(''),
    cl: function(){
       viewModel.selectedDocument('');
    }
};

/* load data */
viewModel.allDocumentTypes.push(new documentType(1,'Test 1'));
viewModel.allDocumentTypes.push(new documentType(2,'Test 2'));
ko.applyBindings(viewModel);

我期望,在我点击“CLEAR VALUE!”的span后,select中将选择选项“choose...”,但实际上没有发生。viewModel中的值被设置为空字符串,这是正确的,但用户仍然看到旧值在select中。
有什么办法可以解决吗?
谢谢你的帮助 :)
3个回答

11
你必须将绑定类型从"selectedOptions"更改为"value"。下一步是在cl函数中设置viewModel.selectedDocument:
viewModel.selectedDocument(null);

3
在某些情况下,将可观察值设置为null可能无效,例如:
// This is the array
self.timePeriods = ko.observableArray([
    new timePeriod("weekly", 7),
    new timePeriod("fortnightly", 14),
    new timePeriod("monthly", 30),
    new timePeriod("half yearly", 180),
    new timePeriod("yearly", 365)
]);

以下是HTML部分:

以下是 HTML 部分:

<select data-bind="options: timePeriods, 
                            optionsText: function(item) { 
                               return item.Name;
                            }, 
                            value: selectedPeriod"
                            class="combo">

您不能通过以下方式重置选择框:

self.selectedPeriod(null); // but this will not work

相反,请写成这样:

self.selectedPeriod(self.timePeriods()[0]);

0
<script>
var vm ={ 
CountryId=ko.observable(),
QC=ko.observable(),
clearSelectedStation: function () {
this.CountryId(null);   //DropDown
this.QC('');   //Textbox
}
};
</script>

这里是一个HTML

 <input type="text" tabindex="10" data-bind="value:QC"/>

<select class="dropdownlist" data-bind="options:Countries, value: CountryId, 
optionsCaption: '--Select--', optionsText: 'CountryName', optionsValue: 'CountryId'">


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接