Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 220
rampion Avatar asked Mar 18 '13 16:03

rampion


People also ask

How to bind click event in knockout?

The function you want to bind to the element's click event. You can reference any JavaScript function - it doesn't have to be a function on your view model. You can reference a function on any object by writing click: someObject. someFunction .

How do you activate a KnockoutJS model?

Activating Knockout But since the browser doesn't know what it means, you need to activate Knockout to make it take effect. To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel);

What is data bind in knockout JS?

The "data-bind" attribute contains a collection of comma-separated options for how Knockout should bind a view model property to an HTML element. The two examples above use only a single option: the "value" binding handler.

What is value binding?

The value binding is the most frequently used binding in DotVVM. It allows you to bind a property in the viewmodel to a property of a control in the DOTHTML file, or just render the value as a text.


1 Answers

You need the optionsCaption binding set.

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

Updated Fiddle

like image 69
Joe Avatar answered Sep 27 '22 22:09

Joe