2011-11-15 21 views
3

我有這個簡單的knockout.js應用:Knockoutjs明確選擇的值在組合框中

查看:

<select data-bind="options: allDocumentTypes , optionsCaption: 'Choose ...', optionsValue: 'id', optionsText: 'name', selectedOptions: selectedDocument"></select> 
<span data-bind="click: cl">CLEAR VALUE!</span> 

和這個簡單的視圖模型:

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!」,在選擇選項中將選擇「選擇...」,但不會發生。 viewModel中的值設置爲「」(空字符串),這是正確的,但用戶仍然在select中看到舊值。

有沒有辦法做到這一點?

感謝您的幫助:)

回答

9

您必須更改綁定類型爲「價值」而不是「selectedOptions」。下一步是設置viewModel.selectedDocument在CL功能:

viewModel.selectedDocument(null); 
+1

這actualy解決我的問題。謝謝 :) – clpx

2

在某些情況下,可觀察到的設定值設置爲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:

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

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

你不能復位選擇框

insetead這樣寫:

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'">