Search code examples
javascriptknockout.jsknockout-components

Knockout Components Select Options


I've been ripping my hair out, can someone please save me...

I want to create a simple knockout component that renders a select list based on JSON object. This works when I use a simple string array, but when I use the JSON object, with id and name attributes that are being bound using optionsText and optionsValue, I get a drop down list with [object object].

Any help would be greatly appreciated.

        ko.components.register("organization-select", {
            viewModel: function (params) {
                var self = this;
                self.organizationList = ko.observableArray([]);
                self.organizationList(["foo", "bar"]); //this works

                //this doesn't work Result => [Object Object],[Object Object]
                self.organizationList([{ "id": 1, "name": "foo" }, { "id": 2, "name": "bar" }]); 
            },

            template: 'Organizations: <select data-bind="options: organizationList, optionsText: "name", optionsValue: "id""></options>'
            //this works with simple array of strings
            //template: 'Organizations: <select data-bind="options: organizationList"></options>'
        });
        ko.applyBindings();
    });

Solution

  • Quotes look messed up:

    template: 'Organizations: <select data-bind="options: organizationList, optionsText: "name", optionsValue: "id""></options>'
    // Here ------------------------------------^ but then ------------------------------^
    

    ...and so the data-bind option actually just contains

    data-bind="options: organizationList, optionsText: "
    

    You need to escape those embedded quotes. Probably the easiest thing is to use escaped singles:

    template: 'Organizations: <select data-bind="options: organizationList, optionsText: \'name\', optionsValue: \'id\'"></options>'