我使用 knockoutjs 自定义绑定(bind)制作了一个 Bootstrap 选择器,我从我的 flask View (即用户列表)中为其提供数据。我只需要从 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 个用户。我需要为此编写一些 knockout 代码或 JS 代码吗?
最佳答案
以下是限制复选框选中次数的方法:
// 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>
请密切注意我已通过在 View 中使用 ()
有很多方法可以做到这一点,这只是其中一种。
关于javascript - 带有 knockoutjs 绑定(bind)的 bootstrap-select 从 4 个选项中选择 2 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20268929/