I want to be able to set the value of a knockout observable
that is the value
of a select
with case-insensitivity
. So in my below example passing justin
would set the selectedValue
to Justin
.
HTML
<select id="people" data-bind="options: peopleList, value: selectedPerson, optionsCaption: 'Choose...'">
</select>
JS
function MyViewModel(defaultPerson) {
var self = this;
self.selectedPerson = ko.observable(defaultPerson);
self.peopleList = ko.observableArray(["Justin", "Sam", "Chris", "John"]);
}
$(function(){
var person = 'justin';
var viewModel = new MyViewModel(person);
ko.applyBindings(viewModel);
});
You can can render options by yourself and don't use options
binding. This will allow you to convert value to lowercase:
<select id="people" data-bind="value: selectedPerson, optionsCaption: 'Choose...'">
<option value=''>Choose...</option>
<!-- ko foreach: peopleList -->
<option data-bind='value: $data.toLowerCase(), text: $data'></option>
<!-- /ko -->
</select>
Here is working jsFiddle
Use optionsValue
and optionsText
bindings to render entries "as is" while keeping value case-insensitive.
function MyViewModel(defaultPerson) {
var self = this;
var Person = function(name) {
this.name = name;
this.ciName = name.toLowerCase();
};
self.selectedPerson = ko.observable(defaultPerson);
self.ciSelectedPerson = ko.computed(function() {
return self.selectedPerson().toLowerCase();
});
self.peopleList = ko.observableArray(
["Justin", "Sam", "Chris", "John"].map(
function(s) { return new Person(s) }));
}
Markup:
<select id="people" data-bind="options: peopleList, optionsValue: 'ciName', optionsText: 'name', value: ciSelectedPerson, optionsCaption: 'Choose...'">
</select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With