如何使selectedValue允许不区分大小写

时间:2013-08-09 10:06:05

标签: javascript jquery knockout.js

我希望能够使用 observable 设置value select的淘汰赛case-insensitivity的值。因此,在我的下面示例中,传递justin会将selectedValue设置为Justin

无效: jsfiddle

工作: 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);
});

2 个答案:

答案 0 :(得分:1)

您可以自己渲染选项,也不要使用options绑定。这将允许您将值转换为小写:

<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>

这是有效的jsFiddle

答案 1 :(得分:1)

使用optionsValueoptionsText绑定“按原样”呈现条目,同时保持值不区分大小写。

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) }));
}

标记:

<select id="people" data-bind="options: peopleList, optionsValue: 'ciName', optionsText: 'name', value: ciSelectedPerson, optionsCaption: 'Choose...'">
</select>