Reputation: 4051
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. 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. Do i need to write some knockout code or JS code for this.
Upvotes: 2
Views: 1429
Reputation: 11558
Here is how you would go about limiting your checkboxes selected count:
// 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>
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.
Upvotes: 1