0

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?

4
  • 1
    I can't reproduce your error: jsfiddle.net/ogLpxc0L/1. Could you update the fiddle, please? Commented Jun 18, 2017 at 11:28
  • @JoseLuis Thank you, I found what causes the issue: selectedUser can't get a 0 value, when I set it with a 0 value it gets undefined. Why selectedUser can't be 0? I added a `console.log() to the fiddle. Commented Jun 18, 2017 at 17:42
  • In this update of the fiddle (jsfiddle.net/ogLpxc0L/4) you can select the '0'. I added a row, Selected, to show the actual value selected. Also, I changed the first user to have id = 0. In this link (knockoutjs.com/documentation/options-binding.html) it says that undefined value shows the default option. Commented Jun 18, 2017 at 18:18
  • 1
    @JoseLuis That means that value can't get a value that is not one of the options of the select, I managed to solve it, if you want you can write it as an answer and I'll accept it. Commented Jun 18, 2017 at 19:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help !! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.