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



我希望能够设置敲除observable的值,该值是具有case-insensitivityselectvalue。因此,在我下面的例子中,传递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);
});

您可以自己渲染选项,而不使用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

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

相关内容

  • 没有找到相关文章

最新更新