Skip to content

Instantly share code, notes, and snippets.

@morkeleb
Created September 20, 2015 18:56
Show Gist options
  • Save morkeleb/1deead57e2d8259a88d5 to your computer and use it in GitHub Desktop.
Save morkeleb/1deead57e2d8259a88d5 to your computer and use it in GitHub Desktop.
Simple multiselect using bootstrap and knockout
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
<span data-bind="text: selection_size"/> <span data-bind="localize:'Client.Management.NumberOfTagsSelected'"/>
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1" data-bind="foreach: sorted_values">
<li role="presentation"><a data-bind="click: selection_changed"><input type=checkbox data-bind="checked: selected"/> <span data-bind="text: Title"></a></li>
</ul>
</div>
module.exports = function () {
var vm = {
selection_size: ko.observable(0)
};
function selection_changed(item, jqueryEvent) {
item.selected(!item.selected());
jqueryEvent.stopPropagation();
vm.selected(vm.values().filter(function (item) {
return item.selected();
}).map(function (item) {
return item.Href;
}));
vm.selection_size(vm.selected().length);
return true;
}
function mark_selection(selected_options) {
var i=0;
vm.values().map(function (item) {
if(selected_options.indexOf(item.Href || item) > -1){
item.selected(true);
i++;
} else {
item.selected(false);
}
});
vm.selection_size(i);
}
function sort(a,b) {
if(a.selected() != b.selected()){
if(a.selected()){
return -1;
}
if(b.selected()){
return 1;
}
}
if (a.Title > b.Title) {
return 1;
}
if (a.Title < b.Title) {
return -1;
}
return 0;
}
vm.load = function(params){
vm.values = ko.pureComputed(function () {
var p = params.values;
if(ko.isObservable(p)){
p = p();
}
return p.map(function (item) {
return {
Title: item.Title || item,
Href : item.Href || item,
selected: ko.observable(false),
selection_changed: selection_changed
}
});
},vm);
vm.sorted_values = ko.pureComputed(function () {
var sorted = vm.values();
sorted.sort(sort);
return sorted;
})
if(params.selected) {
vm.selected = params.selected;
vm.selected.subscribe(mark_selection);
mark_selection(vm.selected());
}
};
return vm;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment