How to pre-select option in select dropdown when w

2019-08-30 05:39发布

问题:

This is actually related to a question I had asked here. But since, this was in a slightly different context, I thought it was best if I created a new question altogether.

I know how to pre-select an option in the dropdown when I'm working with a simple array of strings.

Array of strings

View

<select id="first" data-bind="options: firstDropdownOptions, value: selectedFirstOptionValue"></select>

View Model

firstDropdownOptions: ko.observableArray(['USA','UK','Other']);
selectedFirstOptionValue: ko.observable('UK');

..but how do I pre-select an option if it's an array of objects?

Array of objects

View

<select id="second" data-bind="options: secondDropdownOptions, optionsText: 'title', value: selectedSecondOptionValue"></select>

View model

secondDropdownOptions: ko.observableArray([
    { value: -1, title: 'Select Type' },
    { value: 1, title: 'Option New 1' },
    { value: 2, title: 'Option New 2' }, // I want this option selected initially
    { value: 3, title: 'Option New 3' }
]);
// similarly, how to pre-select the 3rd option in this case?
selectedSecondOptionValue: ko.observable('')

This is the fiddle here.

I've tried passing the entire object here, the value only as an integer. I even thought maybe if I try to render the <select> dropdown in a way that I can set the attributes explicitly, then maybe I can try and manipulate the selected attribute for it. But I did not get the expected results. Here is the fiddle for this.

<select data-bind="foreach: secondDropdownOptions">
    <option data-bind="attr: { text: title, value: value}"></option>
</select>

In this case, the text does not bind, although the value attribute binds to each <option> in the dropdown.

回答1:

You didn't specify the optionsValue parameter. According to the docs :

...However, if you want to let the user choose from an array of arbitrary JavaScript objects (not merely strings), then see the optionsText and optionsValue parameter.

The select for an array of objects:

<select id="second" data-bind="options: secondDropdownOptions, optionsText: 'title', optionsValue: 'value', value: selectedSecondOptionValue"></select>

Working fiddle.



回答2:

Make the options list a separate variable that can be used by both of your observables.

var options = [
    { value: -1, title: 'Select Type' },
    { value: 1, title: 'Option New 1' },
    { value: 2, title: 'Option New 2' }, // I want this option selected initially
    { value: 3, title: 'Option New 3' }
];

var vm = {
  secondDropdownOptions: ko.observableArray(options),
  selectedSecondOptionValue: ko.observable(options[2])
};

Probaby what you really want to do is use the optionsValue binding, as Bogdan Goie suggested, in which case your initialization is simply

  selectedSecondOptionValue: ko.observable(2)

Incidentally, you might also want to look at the optionsCaption parameter as an alternative to your -1 option.



标签: knockout.js