I want to turn array to select option via knockout js, I know 3 methods for this case, but none of these work perfectly with what I really want, what I want is:
- Set default option
Choose an option - get selected value
- set
attrfor options
Each method has own issue, but last method has default option and can get selected value, but can't set attr, any idea?
Method 1:
Error:
Uncaught Error: The binding 'value' cannot be used with virtual elements
Status: not working
function myfunc() {
var self = this;
self.estimate = ko.observableArray([]);
self.selectedValue = ko.observable();
var obj = [{
method_title: "blah blah",
price: "1000"
},
{
method_title: "blah blah 2",
price: "2000"
}
];
self.estimate(obj);
self.selectedValue.subscribe(function(value) {
alert(value);
});
}
ko.applyBindings(new myfunc());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select id="method">
<option value="0">Choose an option</option>
<!-- ko foreach: estimate, value: selectedValue -->
<option data-bind="text: method_title,
attr: { 'data-price': price, 'value': method_title },
text: method_title"></option>
<!-- /ko -->
</select>
Method 2:
Status: working but I could not add default option, it looped everytime.
function myfunc() {
var self = this;
self.estimate = ko.observableArray([]);
self.selectedValue = ko.observable();
var obj = [{
method_title: "blah blah",
price: "1000"
},
{
method_title: "blah blah 2",
price: "2000"
}
];
self.estimate(obj);
self.selectedValue.subscribe(function(value) {
alert(value);
});
}
ko.applyBindings(new myfunc());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select id="method" data-bind="foreach: estimate,value: selectedValue">
<option value="0">Choose an option</option>
<option data-bind="text: method_title,attr: {'data-price': price, value: method_title}"></option>
</select>
Method 3:
Status: working but I could not set attr
function myfunc() {
var self = this;
self.estimate = ko.observableArray([]);
self.selectedValue = ko.observable();
var obj = [{
method_title: "blah blah",
price: "1000"
},
{
method_title: "blah blah 2",
price: "2000"
}
];
self.estimate(obj);
self.selectedValue.subscribe(function(value) {
alert(value);
});
}
ko.applyBindings(new myfunc());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select id="method" data-bind="value: selectedValue,options: estimate,
optionsText: 'method_title',
optionsValue: 'method_title',
optionsCaption: 'Choose an option'"></select>
selectelements before Knockout ever sees those. IE 8 for example does that.