简体   繁体   English

如果没有值,则设置select的默认值

[英]Set default value of select if no value

I have this select : 我有这个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. 如果$root.selectedUser = 0则仅需要选择默认值(“选择一个”),否则不需要默认值。

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.) (如果$root.selectedUser = 0它将显示列表的第一个值,而不是默认值。)

Any idea on how to achieve that? 关于如何实现这一点的任何想法?

If this ModelView: 如果此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. 我有一个ID为0的用户。

If you save in your observable any value that is an Id, it selects this option. 如果您在可观察值中保存一个Id值,它将选择此选项。 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. 如果保存任何值或undefined ,则显示默认选项。

This fiddle shows this example. 这个小提琴显示了这个例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM