[英]bootstrap-select with knockoutjs binding to select 2 out of 4 options
I have made a bootstrap-select picker using knockoutjs custom binding , I am providing it data from my flask view which is the list of users. 我已经使用基因敲除自定义绑定创建了一个引导选择拾取器,我从烧瓶视图(它是用户列表)中提供了数据。 I need to select 2 out of 4 options only.
我只需要选择4个选项中的2个。 Please have a look at my select tag
请看看我的选择标签
<select data-bind="selectPicker: selectPicking, selectPickerOptions: { options: allusers, optionsText: 'uname', optionsValue: 'uuid' }" data-live-search="true" multiple="true" ></select>
Now I am getting this 现在我得到这个
I want to select only 2 out of 4 options how can I do this , as such there is no options size attribute in HTML or HTML5 where I can define that I would like to select only 4 users from n number of users. 我只想从4个选项中选择2个,我该怎么做,因此在HTML或HTML5中没有选项size属性,可以定义从n个用户中仅选择4个用户。 Do i need to write some knockout code or JS code for this.
我是否需要为此编写一些敲除代码或JS代码。
Here is how you would go about limiting your checkboxes selected count: 以下是限制复选框选择数量的方法:
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: 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>
Pay close attention to the fact that I have made the checked binding of the checkbox a one way binding (a read only property) by executing it in the view using ()
请密切注意我通过使用
()
在视图中执行复选框,使复选框的选中绑定成为一种单向绑定(只读属性)这一事实
There are many ways of doing this and this is only one. 有很多方法可以做到这一点,但这仅仅是一种。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.