knockout multiselect selectedOptions contains values instead of objects

前端 未结 3 1375
一整个雨季
一整个雨季 2020-12-19 17:07

I have a select with the attribute multiple. For each option in the select I want the title attribute set (which shows a tooltip). I also want to retrieve the selected optio

相关标签:
3条回答
  • 2020-12-19 17:37

    Use options and optionsText bindings instead of foreach:

    <select multiple style="width: 150px;" size=15 
        data-bind="options: options, optionsText: 'Name', selectedOptions: selectedOptions">
    <option data-bind="text: Name, attr: { 'title': Name}"></option>
    </select>
    

    Here is demo: http://jsfiddle.net/p5E8y/

    0 讨论(0)
  • 2020-12-19 17:56

    Similar to @MuhammadRaheel, I used optionsAfterRender:

    <select data-bind="optionsAfterRender: myFunc, ...">
    

    But I needed to use ko.applyBindingsToNode:

    var self.myFunc = function(option, item) {
        ko.applyBindingsToNode(option, { attr: { title: 'Tooltip!' } }, item);
    }
    
    0 讨论(0)
  • 2020-12-19 17:57

    Try your html like this

    <select 
        data-bind="
            options: options,
            selectedOptions : selectedOptions,
            optionsText: 'Name',
            optionsCaption: 'Choose...'
        "
     size="5" multiple="true"></select>
    

    Demo

    See the console for output

    EDITS :

    To add attributes to option you need to use optionsAfterRender.
    This is available only in version 3.1.0. I noticed your fiddle is using 3.0.0.

    <select 
        data-bind="
            options: options,
            selectedOptions : selectedOptions,
            optionsText: 'Name',
            optionsAfterRender: $root.setTitle
        "
     size="5" multiple="true"></select><br />
    <button data-bind="click: showSelectedOptions">Show selection</button>
    

    And create a fnction

    self.setTitle = function(option, item) {
        option.title = item.Name
    }  
    

    Demo

    Reference See Note 2

    0 讨论(0)
提交回复
热议问题