clpx
clpx

Reputation: 103

Knockoutjs clear selected value in combobox

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:)

Upvotes: 4

Views: 6816

Answers (3)

Arsen Khachaturyan
Arsen Khachaturyan

Reputation: 8340

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]);

Upvotes: 3

Srinivas
Srinivas

Reputation: 23999

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

here is a 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'">

Upvotes: 0

Jupin
Jupin

Reputation: 555

You must change binding type to "value" instead of "selectedOptions". Next step is to set viewModel.selectedDocument in cl function:

viewModel.selectedDocument(null);

Upvotes: 11

Related Questions