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?
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 .
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);
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.
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.
You need the optionsCaption binding set.
<select data-bind="options: myOptions, value: myValue, optionsCaption: 'select...'"></select>
Updated Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With