Skip to content
Anders Malmgren edited this page Nov 1, 2013 · 12 revisions

Any object of type array including observableArray can be bound to a select element.

<select data-name="items"></select>

By convention it will look for a selectedItems (Multiselect) or selectedItem (Dropdown) member

TestViewModel = function() {
    this.items = ["1", "2", "3"];
    this.selectedItem = ko.observable();
};

http://jsfiddle.net/MDHCK/5/

Note

  • companies > selectedCompany
  • classes > selectedClass
  • items > selectedItem

Can select guard

By convention the lib will look for a canChangeSelectedItem

TestViewModel = function() {
    this.items = ["1", "2", "3"];
    this.selectedItem = ko.observable();
    this.canChangeSelectedItem = ko.observable(true);
};

http://jsfiddle.net/vRBGE/

Options text and caption

Options caption and text can be bound using traditional data-binding. For text you can use this override.

(function(ko) {
    var orgOptionsApply = ko.bindingConventions.conventionBinders.options.apply;
    ko.bindingConventions.conventionBinders.options.apply = function(name, element, bindings, options, type, data, viewModel) {
        orgOptionsApply.apply(this, arguments);
        
        if (options[0]["name"]) {
            bindings.optionsText = function() { return "name"; };
        }
    };
}(window.ko));

http://jsfiddle.net/tKdf7/1/