【问题标题】:bootstrap-select with knockoutjs binding to select 2 out of 4 optionsbootstrap-select 与 knockoutjs 绑定以选择 4 个选项中的 2 个
【发布时间】:2013-12-14 15:45:46
【问题描述】:

我使用 knockoutjs 自定义绑定制作了一个引导选择选择器,我从我的烧瓶视图(即用户列表)中为其提供数据。我只需要从 4 个选项中选择 2 个。请看我的选择标签

<select data-bind="selectPicker: selectPicking, selectPickerOptions: { options: allusers, optionsText: 'uname', optionsValue: 'uuid' }" data-live-search="true" multiple="true" ></select>

现在我得到了这个

我只想选择 4 个选项中的 2 个,我该怎么做呢,因为 HTML 或 HTML5 中没有选项大小属性,我可以在其中定义我想从 n 个用户中只选择 4 个用户。我是否需要为此编写一些淘汰代码或JS代码。

【问题讨论】:

    标签: javascript jquery twitter-bootstrap knockout.js


    【解决方案1】:

    以下是限制复选框选中数量的方法:

    Link to a fiddle for this

    // Describes what an option is
    var option = function(data){
        this.Name = ko.observable(data.Name);
        this.Selected = ko.observable(data.Selected);
    }
    var optionsVM = function(){
        var self = this;
        // Collection of options
        self.options = ko.observableArray();
        // Find out which items are selected
        self.selectedItems = ko.computed(function(){
            return ko.utils.arrayFilter(self.options(), function(item){
                return item.Selected() === true;
            });
        });
        // Dummy init to put options in the collection
        self.init = function(){
            self.options([
                new option({ Name : "Test 0", Selected: false }),
                new option({ Name : "Test 1", Selected: false }),
                new option({ Name : "Test 2", Selected: false }),
                new option({ Name : "Test 3", Selected: false }),
                new option({ Name : "Test 4", Selected: false })
            ])
        };
    
        self.canCheck = function(item){
            var _canCheck = self.selectedItems().length < 2;
            if (_canCheck){
                // If it can check then just toggle
                item.Selected(!item.Selected());
                return true;
            }
            if (!_canCheck && item.Selected()){
                // if it can't then only allow deselection
                item.Selected(false);
                return true;
            }
        }
    }
    var myOptions = new optionsVM();
    myOptions.init();
    ko.applyBindings(myOptions);
    

    html:

    <ul data-bind="foreach: options">
        <li><label><input type="checkbox" data-bind="click: $parent.canCheck, checked: Selected()" /> <span data-bind="text: Name"></span> <span data-bind="text: Selected"></span></label></li>
    </ul>
    
    <p data-bind="text: selectedItems().length"></p>
    

    请密切注意,我已通过使用() 在视图中执行复选框,将复选框的选中绑定设为单向绑定(只读属性)

    有很多方法可以做到这一点,这只是一种。

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多