Search code examples
knockout.jsbindinghtml-selectdefault

How do you use knockout.js to build a <select> element's <option>s with both text and values, and also set an initially-selected value?


I'm using knockout.js to build a <select> element's <option>s, and also to set its default-selected value. All works as expected until I add optionsValue binding, at which point the dropdown no longer shows the proper initial value on page load.

In other words, this works:

<select data-bind="value: selectedAccount, options: accounts, optionsText: 'name'"></select>

...but this doesn't work:

<select data-bind="value: selectedAccount, options: accounts, optionsText: 'name', optionsValue: 'id'"></select>

Here's my simplified, complete code:

<!doctype html>
<html>
    <head>
        <title>Demo</title>
        <script src='knockout-2.1.0.debug.js'></script>
    </head>
    <body>
        <select data-bind="value: selectedAccount, options: accounts, optionsText: 'name', optionsValue: 'id'"></select>
        <script>
            function QuickTransferViewmodel()
            {
                var self = this;

                self.accounts =
                [
                    { id: 0, name: "Spending" },
                    { id: 1, name: "Savings" }
                ];

                self.selectedAccount = ko.observable(self.accounts[1]);
            }
            ko.applyBindings(new QuickTransferViewmodel());
        </script>
    </body>
</html>

I would expect the dropdown to show "Savings" as selected by default. It only does so if I remove the optionsValue binding.

Thanks in advance!


Solution

  • The optionsValue binding is used to determine which property is used to set the value attribute on the generated option elements.

    This one-line change makes your sample work for me:

    self.selectedAccount = ko.observable(1);

    Your value binding is set to selectedAccount which is an ID, and the values in your generated options elements are indeed the IDs.