I have this select
:
<select data-bind="options: $root.users(), optionsText: 'name', optionsValue: 'id', value: $root.selectedUser, optionsCaption: 'Select one'"></select>
I only need the default value ('Select one') to be selected if $root.selectedUser = 0
otherwise I don't need the default value.
I tried that:
<select data-bind="options: $root.users(), optionsText: 'name', optionsValue: 'id', value: $root.selectedUser, optionsCaption: $root.selectedUser () === 0 ? 'Select one' : ''"></select>
But it's not working. (if $root.selectedUser = 0
it shows the first value of the list instead of the default value.)
Any idea on how to achieve that?
If this ModelView:
var User = function(id, name) {
this.name = name;
this.id = id;
};
var viewModel = {
users : ko.observableArray([
new User(0,"User 1"),
new User(2,"User 2"),
new User(3,"User 3")
]),
selectedUser : ko.observable(0)
};
ko.applyBindings(viewModel);
I have an User that has Id 0.
If you save in your observable any value that is an Id, it selects this option. All of this will select one option:
selectedUser : ko.observable(0)
selectedUser : ko.observable(2)
selectedUser : ko.observable(3)
If you save any value, or undefined
, then the default option is showed.
This fiddle shows this example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.