Reputation: 7448
I want to switch image with drop-down box. The drop-down contains names and should send an URL to the image. (URLs are not visible in the drop down)
I've found this example in the docs:
<select data-bind="options: optionValues, value: selectedOptionValue">
Bot it seems, like optionValues
is observableArray containing only one value and selectedOptionValue
is an observable getting the value selected in the drop box.
My observable array contain structures (hope it's the right expression in JS) looks like:
var PatternExample = function (type, name, example_url) {
this.type = type;
this.name = name;
this.example_url = example_url;
}
Where name should be displayed in the drop-down and example_url used for changing the image.
How could I define the data-binding in the select-element for this data?
EDIT:
Found the answer also in the docs: Example 3: Drop-down list representing arbitrary JavaScript objects, not just strings.
http://knockoutjs.com/documentation/options-binding.html
Upvotes: 0
Views: 958
Reputation: 6045
Try something like this use optionsText
in your select binding
view :
<select data-bind="options:optionValues,optionsText:'name', value: selectedOptionValue"></select>
<img data-bind="attr:{src:selectedOptionValue().url}" style="width:100px;height:100px" />
viewModel:
var ViewModel = function() {
var self=this;
self.selectedOptionValue=ko.observable();
self.optionValues = ko.observableArray([{'type':'','name':'imageone','url':'www.s.com'},{'type':'','name':'imagetwo','url':'www.s1.com'},{'type':'','name':'imagethree','url':'www.s2.com'}]);
self.selectedOptionValue.subscribe(function(data){
console.log(data) // check the output here map url as per your requirement
});
};
ko.applyBindings(new ViewModel()); // This makes Knockout get to work
working sample fiddle here
Upvotes: 1