Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 541
clpx Avatar asked Dec 10 '22 04:12

clpx


2 Answers

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

viewModel.selectedDocument(null);
like image 71
Jupin Avatar answered Dec 26 '22 16:12

Jupin


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]);
like image 23
Arsen Khachaturyan Avatar answered Dec 26 '22 16:12

Arsen Khachaturyan