Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs 'optionsValue' doesn't work

Tags:

knockout.js

I have a code that doesn't work. This is here http://jsfiddle.net/JPBarbosa/uxwTM/4/.

The data bind parameter optionsValue doesn't work like parameter optionsText.

I'm using the same function for both!

<select data-bind="options: times, optionsText: function(item) { return item.toLocaleTimeString(); }, optionsValue: function(item) { return item.toLocaleTimeString(); }, value: selectedTime"></select>

Regards, JP.

like image 861
João Paulo Barbosa Fernandes Avatar asked May 15 '26 07:05

João Paulo Barbosa Fernandes


1 Answers

The object you pass in for optionsValue must be a string corresponding to the name of the property to use as a value. You cannot set it to a value like that, it doesn't work the same way as optionsText unfortunately.

It would be easier to map the times array to the values you want instead.

<select data-bind="options: ko.utils.arrayMap(times(), function (time) { return time.toLocaleTimeString(); }), value: selectedTime"></select>

Though you'll want to keep the mapping code out of your view. So add a computed observable to your view model that returns the mapped values.

var ViewModel = function() {
    // ...
    self.mappedTimes = ko.computed(function () {
        return ko.utils.arrayMap(self.times(), function (time) {
            return time.toLocaleTimeString();
        });
    })
};
<select data-bind="options: mappedTimes, value: selectedTime"></select>

Updated fiddle

like image 161
Jeff Mercado Avatar answered May 17 '26 09:05

Jeff Mercado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!