Reputation: 865
I am using KO MVVM for data binding along with Phonegap (running in ripple emulator), but I am facing an issue.
I am trying to bind selected value's object in select element.
My code is:
HTML
<select data-bind="options: pro(),
optionsText: 'value',
optionsValue: this,
value: province">
</select>
JS
function screen1ViewModel()
{
var self = this;
self.pro = ko.observableArray();
self.province = ko.observable();
}
$(document).ready(function () {
var vm = new screen1ViewModel();
var pro = [{
"symbol": "AB",
"value": "AB - Alberta"
},
{
"symbol": "BC",
"value": "BC - British Columbia"
}];
$.each(pro, function(index, item) {
vm.pro().push(item);
});
});
console.log(vm.province().symbol);
console.log(vm.province().value);
For example, if I select AB - Alberta
from select list, I need it's other keys too.
Any help will be appreciated.
Upvotes: 1
Views: 414
Reputation: 139748
You just need to remove the optionsValue: this,
(although strangely it is working in KO 3.0 and up Demo)
Because the default behavior is that Knockout uses the whole object as the value
if there is no optionsValue
options is specified, which is exactly what you need:
<select data-bind="options: pro, optionsText: 'value', value: province"></select>
Demo JSFiddle.
Upvotes: 2
Reputation: 19882
Your view model seems to be disturbed. Here is a solution
View
<select
data-bind="
options: pro,
optionsText: 'value',
optionsValue: 'symbol',
optionsText: 'value'
value: province
">
</select>
ViewModel
function screen1ViewModel()
{
var self = this;
self.pro = ko.observableArray();
self.province = ko.observable();
self.GetValue = function(){
console.log(self.province())
}
}
$(document).ready(function () {
var vm = new screen1ViewModel();
var pro = [{
"symbol": "AB",
"value": "AB - Alberta"
},
{
"symbol": "BC",
"value": "BC - British Columbia"
}];
vm.pro(pro)
ko.applyBindings(vm)
});
Documentation will be helpful.
EDIT:
Modify the function
self.GetValue = function(){
var obj = {}
ko.utils.arrayForEach(self.pro(),function(item){
if(item.symbol ==self.province()){
obj = item
}
})
console.log(obj)
}
Upvotes: 1