rampion
rampion

Reputation: 89113

knockout.js - setting an empty selection

I'm trying to use knockout.js to populate and manage a <select/> box. I'd like the initial value to be empty.

However, I'm having trouble trying to force the managed value to be null at any time, let alone initially.

For example, consider this fiddle:

HTML:

<select data-bind="options: myOptions, value: myValue"></select> aka
<span data-bind="text: myValue"></span>

<div>
    <button data-bind="click: setMyValue(null)">clear the selection</button>
    <button data-bind="click: setMyValue('one')">select "one"</button>
    <button data-bind="click: setMyValue('four')">select "four"</button>
</div>
<ul data-bind="foreach: log">
    <li>message: <span data-bind="text: message"></span></li>
</ul>

JS:

function Model() {
    var self = this;
    self.myOptions = ['one', 'two', 'three', 'four'];
    self.myValue = ko.observable();
    self.setMyValue = function (val) {
        return function(){
            this.log.push({
                message: "ok, trying to set value as " + val
            });
            self.myValue(val);
        };
    };
    self.log = ko.observableArray([]);
}
var model = new Model();
ko.applyBindings(model);

The select "one" and select "four" buttons work to change the selection by forcing an update of myValue(). However, the clear the selection button doesn't work. The selection is not cleared by myValue(null), which is what I thought was the proper way to do it.

What am I doing wrong?

Upvotes: 19

Views: 12114

Answers (1)

Joe
Joe

Reputation: 82654

You need the optionsCaption binding set.

<select data-bind="options: myOptions, value: myValue, optionsCaption: 'select...'"></select>

Updated Fiddle

Upvotes: 34

Related Questions