Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the selectedValue allow case-insensitive set

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.

Not Working: jsfiddle

Working: jsfiddle

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);
});
like image 489
abc123 Avatar asked Nov 02 '22 16:11

abc123


2 Answers

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

like image 106
Artem Vyshniakov Avatar answered Nov 09 '22 11:11

Artem Vyshniakov


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>
like image 36
rkhayrov Avatar answered Nov 09 '22 10:11

rkhayrov