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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…