I have this simple knockout.js application:
View:
<select data-bind="options: allDocumentTypes , optionsCaption: 'Choose ...', optionsValue: 'id', optionsText: 'name', selectedOptions: selectedDocument"></select>
<span data-bind="click: cl">CLEAR VALUE!</span>
and this simple 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);
I would expect, that after i click on span "CLEAR VALUE!", in select will be selected option "choose...", but it is not happening. The value in viewModel is set to "" (empty string), which is right, but user still see old value in select.
Is there any way to do that?
Thanks for helping:)
You must change binding type to "value" instead of "selectedOptions". Next step is to set viewModel.selectedDocument in cl function:
viewModel.selectedDocument(null);
In some cases setting the observable value to null
will not work, for example :
// 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)
]);
And below is the HTML
part:
<select data-bind="options: timePeriods,
optionsText: function(item) {
return item.Name;
},
value: selectedPeriod"
class="combo">
You can't reset select box by:
self.selectedPeriod(null); // but this will not work
Insetead write this:
self.selectedPeriod(self.timePeriods()[0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With