Set HTML <select> default text when its data-bind observable array is empty

48 views Asked by At

I am using knockout.js options binding for a drop-down list something like this:

<select data-bind="options: availableCountries,
                   optionsText: 'countryName',
                   value: selectedCountry,
                   optionsCaption: 'Choose...'"></select>

If the observable array used for the data-bind is empty, i.e. there will be no options for the dropdown, I want the select element to display some unselectable text like "Sorry, there are no available countries". How to do this?

Is there some html setting in the select element or some knockout.js specific method with the data-bind to display text when there are no options?

1

There are 1 answers

0
Gary Barrett On

Building on this answer, I set up an observable property for my optionsCaption and subscribed to my observable array so that when the observable array changes, I then also change optionsCaption like this, which works:

self.myOptionsCaption = ko.observable(null);

self.availableCountries.subscribe(function () {
            self.myOptionsCaption("Choose...");
            if (self.availableCountries().length === 0) {
                self.myOptionsCaption("Sorry, there are no available countries");
            }
        });

<select data-bind="options: availableCountries,
                   optionsText: 'countryName',
                   value: selectedCountry,
                   optionsCaption: myOptionsCaption(),
                   disable: availableCountries()==0"></select>

You may notice that I also decided to disable the select when the observable array is empty.