Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

javascript - knockout multiselect selectedOptions contains values instead of objects

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 options as an array of objects. I managed to get what I want except for the fact that the selected options doesnt return an array of objects but an array of valueTexts. I can't figure out how I get objects in that array.

This is the code I got so far:

HTML:

<select multiple style="width: 150px;" size=15 
        data-bind="foreach: options, selectedOptions: selectedOptions">
    <option data-bind="text: Name, attr: { 'title': Name}"></option>
</select><br />
<button data-bind="click: showSelectedOptions">Show selection</button>

Javascript:

function Option(id, name){
    var self = this;

    self.Id = id;
    self.Name = name;
}

function ViewModel(){
    var self = this;

    self.options = ko.observableArray([
        new Option(0, "NormalText"),
        new Option(1, "AnotherText"),
        new Option(2, "WaaaaaaaaaaaaaaaayTooLongText")
    ]);
    self.selectedOptions = ko.observableArray([]);

    self.showSelectedOptions = function(){
        alert(self.selectedOptions());
        //what I would like to have:
        //if (self.selectedOptions().length > 0)
        //    alert(self.selectedOptions()[0].Name);
    }
}

ko.applyBindings(new ViewModel());

And the fiddle link for demonstration: http://jsfiddle.net/c63Bb/1/

What do I need to add or change so the array selectedOptions contains objects instead of strings?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...