2 * Bootstrap Multiselect (https://github.com/davidstutz/bootstrap-multiselect)
4 * Apache License, Version 2.0:
5 * Copyright (c) 2012 - 2015 David Stutz
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
8 * use this file except in compliance with the License. You may obtain a
9 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 * License for the specific language governing permissions and limitations
17 * BSD 3-Clause License:
18 * Copyright (c) 2012 - 2015 David Stutz
19 * All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions are met:
23 * - Redistributions of source code must retain the above copyright notice,
24 * this list of conditions and the following disclaimer.
25 * - Redistributions in binary form must reproduce the above copyright notice,
26 * this list of conditions and the following disclaimer in the documentation
27 * and/or other materials provided with the distribution.
28 * - Neither the name of David Stutz nor the names of its contributors may be
29 * used to endorse or promote products derived from this software without
30 * specific prior written permission.
32 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
33 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
34 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
35 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
36 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
37 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
38 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
39 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
40 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
41 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
42 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 "use strict";// jshint ;_;
47 if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) {
48 ko.bindingHandlers.multiselect = {
49 after: ['options', 'value', 'selectedOptions', 'enable', 'disable'],
51 init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
52 var $element = $(element);
53 var config = ko.toJS(valueAccessor());
55 $element.multiselect(config);
57 if (allBindings.has('options')) {
58 var options = allBindings.get('options');
59 if (ko.isObservable(options)) {
63 setTimeout(function() {
64 var ms = $element.data('multiselect');
66 ms.updateOriginalOptions();//Not sure how beneficial this is.
67 $element.multiselect('rebuild');
70 disposeWhenNodeIsRemoved: element
75 //value and selectedOptions are two-way, so these will be triggered even by our own actions.
76 //It needs some way to tell if they are triggered because of us or because of outside change.
77 //It doesn't loop but it's a waste of processing.
78 if (allBindings.has('value')) {
79 var value = allBindings.get('value');
80 if (ko.isObservable(value)) {
84 setTimeout(function() {
85 $element.multiselect('refresh');
88 disposeWhenNodeIsRemoved: element
89 }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
93 //Switched from arrayChange subscription to general subscription using 'refresh'.
94 //Not sure performance is any better using 'select' and 'deselect'.
95 if (allBindings.has('selectedOptions')) {
96 var selectedOptions = allBindings.get('selectedOptions');
97 if (ko.isObservable(selectedOptions)) {
101 setTimeout(function() {
102 $element.multiselect('refresh');
105 disposeWhenNodeIsRemoved: element
106 }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
110 var setEnabled = function (enable) {
111 setTimeout(function () {
113 $element.multiselect('enable');
115 $element.multiselect('disable');
119 if (allBindings.has('enable')) {
120 var enable = allBindings.get('enable');
121 if (ko.isObservable(enable)) {
124 setEnabled(enable());
126 disposeWhenNodeIsRemoved: element
127 }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
133 if (allBindings.has('disable')) {
134 var disable = allBindings.get('disable');
135 if (ko.isObservable(disable)) {
138 setEnabled(!disable());
140 disposeWhenNodeIsRemoved: element
141 }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
143 setEnabled(!disable);
147 ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
148 $element.multiselect('destroy');
152 update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
153 var $element = $(element);
154 var config = ko.toJS(valueAccessor());
156 $element.multiselect('setOptions', config);
157 $element.multiselect('rebuild');
162 function forEach(array, callback) {
163 for (var index = 0; index < array.length; ++index) {
164 callback(array[index], index);
169 * Constructor to create a new multiselect using the given select.
171 * @param {jQuery} select
172 * @param {Object} options
173 * @returns {Multiselect}
175 function Multiselect(select, options) {
177 this.$select = $(select);
178 this.options = this.mergeOptions($.extend({}, options, this.$select.data()));
180 // Placeholder via data attributes
181 if (this.$select.attr("data-placeholder")) {
182 this.options.nonSelectedText = this.$select.data("placeholder");
186 // We have to clone to create a new reference.
187 this.originalOptions = this.$select.clone()[0].options;
189 this.searchTimeout = null;
190 this.lastToggledInput = null;
192 this.options.multiple = this.$select.attr('multiple') === "multiple";
193 this.options.onChange = $.proxy(this.options.onChange, this);
194 this.options.onSelectAll = $.proxy(this.options.onSelectAll, this);
195 this.options.onDeselectAll = $.proxy(this.options.onDeselectAll, this);
196 this.options.onDropdownShow = $.proxy(this.options.onDropdownShow, this);
197 this.options.onDropdownHide = $.proxy(this.options.onDropdownHide, this);
198 this.options.onDropdownShown = $.proxy(this.options.onDropdownShown, this);
199 this.options.onDropdownHidden = $.proxy(this.options.onDropdownHidden, this);
200 this.options.onInitialized = $.proxy(this.options.onInitialized, this);
201 this.options.onFiltering = $.proxy(this.options.onFiltering, this);
203 // Build select all if enabled.
204 this.buildContainer();
206 this.buildDropdown();
207 this.buildSelectAll();
208 this.buildDropdownOptions();
211 this.updateButtonText();
212 this.updateSelectAll(true);
214 if (this.options.enableClickableOptGroups && this.options.multiple) {
215 this.updateOptGroups();
218 this.options.wasDisabled = this.$select.prop('disabled');
219 if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) {
223 this.$select.wrap('<span class="multiselect-native-select" />').after(this.$container);
224 this.options.onInitialized(this.$select, this.$container);
227 Multiselect.prototype = {
231 * Default text function will either print 'None selected' in case no
232 * option is selected or a list of the selected options up to a length
233 * of 3 selected options.
235 * @param {jQuery} options
236 * @param {jQuery} select
239 buttonText: function(options, select) {
240 if (this.disabledText.length > 0
241 && (select.prop('disabled') || (options.length == 0 && this.disableIfEmpty))) {
243 return this.disabledText;
245 else if (options.length === 0) {
246 return this.nonSelectedText;
248 else if (this.allSelectedText
249 && options.length === $('option', $(select)).length
250 && $('option', $(select)).length !== 1
253 if (this.selectAllNumber) {
254 return this.allSelectedText + ' (' + options.length + ')';
257 return this.allSelectedText;
260 else if (options.length > this.numberDisplayed) {
261 return options.length + ' ' + this.nSelectedText;
265 var delimiter = this.delimiterText;
267 options.each(function() {
268 var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text();
269 selected += label + delimiter;
272 return selected.substr(0, selected.length - this.delimiterText.length);
276 * Updates the title of the button similar to the buttonText function.
278 * @param {jQuery} options
279 * @param {jQuery} select
280 * @returns {@exp;selected@call;substr}
282 buttonTitle: function(options, select) {
283 if (options.length === 0) {
284 return this.nonSelectedText;
288 var delimiter = this.delimiterText;
290 options.each(function () {
291 var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text();
292 selected += label + delimiter;
294 return selected.substr(0, selected.length - this.delimiterText.length);
297 checkboxName: function(option) {
298 return false; // no checkbox name
303 * @param {jQuery} element
306 optionLabel: function(element){
307 return $(element).attr('label') || $(element).text();
312 * @param {jQuery} element
315 optionClass: function(element) {
316 return $(element).attr('class') || '';
319 * Triggered on change of the multiselect.
321 * Not triggered when selecting/deselecting options manually.
323 * @param {jQuery} option
324 * @param {Boolean} checked
326 onChange : function(option, checked) {
330 * Triggered when the dropdown is shown.
332 * @param {jQuery} event
334 onDropdownShow: function(event) {
338 * Triggered when the dropdown is hidden.
340 * @param {jQuery} event
342 onDropdownHide: function(event) {
346 * Triggered after the dropdown is shown.
348 * @param {jQuery} event
350 onDropdownShown: function(event) {
354 * Triggered after the dropdown is hidden.
356 * @param {jQuery} event
358 onDropdownHidden: function(event) {
362 * Triggered on select all.
364 onSelectAll: function() {
368 * Triggered on deselect all.
370 onDeselectAll: function() {
374 * Triggered after initializing.
376 * @param {jQuery} $select
377 * @param {jQuery} $container
379 onInitialized: function($select, $container) {
383 * Triggered on filtering.
385 * @param {jQuery} $filter
387 onFiltering: function($filter) {
391 buttonClass: 'btn btn-default',
394 buttonContainer: '<div class="btn-group" />',
397 selectedClass: 'active',
398 // Maximum height of the dropdown menu.
399 // If maximum height is exceeded a scrollbar will be displayed.
401 includeSelectAllOption: false,
402 includeSelectAllIfMoreThan: 0,
403 selectAllText: ' Select all',
404 selectAllValue: 'multiselect-all',
405 selectAllName: false,
406 selectAllNumber: true,
407 selectAllJustVisible: true,
408 enableFiltering: false,
409 enableCaseInsensitiveFiltering: false,
410 enableFullValueFiltering: false,
411 enableClickableOptGroups: false,
412 enableCollapsibleOptGroups: false,
413 filterPlaceholder: 'Search',
414 // possible options: 'text', 'value', 'both'
415 filterBehavior: 'text',
416 includeFilterClearBtn: true,
417 preventInputChangeEvent: false,
418 nonSelectedText: 'None selected',
419 nSelectedText: 'selected',
420 allSelectedText: 'All selected',
422 disableIfEmpty: false,
426 button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"><span class="multiselect-selected-text"></span> <b class="caret"></b></button>',
427 ul: '<ul class="multiselect-container dropdown-menu"></ul>',
428 filter: '<li class="multiselect-item multiselect-filter"><div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
429 filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default multiselect-clear-filter" type="button"><i class="glyphicon glyphicon-remove-circle"></i></button></span>',
430 li: '<li><a tabindex="0"><label></label></a></li>',
431 divider: '<li class="multiselect-item divider"></li>',
432 liGroup: '<li class="multiselect-item multiselect-group"><label></label></li>'
436 constructor: Multiselect,
439 * Builds the container of the multiselect.
441 buildContainer: function() {
442 this.$container = $(this.options.buttonContainer);
443 this.$container.on('show.bs.dropdown', this.options.onDropdownShow);
444 this.$container.on('hide.bs.dropdown', this.options.onDropdownHide);
445 this.$container.on('shown.bs.dropdown', this.options.onDropdownShown);
446 this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden);
450 * Builds the button of the multiselect.
452 buildButton: function() {
453 this.$button = $(this.options.templates.button).addClass(this.options.buttonClass);
454 if (this.$select.attr('class') && this.options.inheritClass) {
455 this.$button.addClass(this.$select.attr('class'));
457 // Adopt active state.
458 if (this.$select.prop('disabled')) {
465 // Manually add button width if set.
466 if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') {
468 'width' : '100%', //this.options.buttonWidth,
469 'overflow' : 'hidden',
470 'text-overflow' : 'ellipsis'
472 this.$container.css({
473 'width': this.options.buttonWidth
477 // Keep the tab index from the select.
478 var tabindex = this.$select.attr('tabindex');
480 this.$button.attr('tabindex', tabindex);
483 this.$container.prepend(this.$button);
487 * Builds the ul representing the dropdown menu.
489 buildDropdown: function() {
492 this.$ul = $(this.options.templates.ul);
494 if (this.options.dropRight) {
495 this.$ul.addClass('pull-right');
498 // Set max height of dropdown menu to activate auto scrollbar.
499 if (this.options.maxHeight) {
500 // TODO: Add a class for this option to move the css declarations.
502 'max-height': this.options.maxHeight + 'px',
503 'overflow-y': 'auto',
504 'overflow-x': 'hidden'
508 if (this.options.dropUp) {
510 var height = Math.min(this.options.maxHeight, $('option[data-role!="divider"]', this.$select).length*26 + $('option[data-role="divider"]', this.$select).length*19 + (this.options.includeSelectAllOption ? 26 : 0) + (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering ? 44 : 0));
511 var moveCalc = height + 34;
514 'max-height': height + 'px',
515 'overflow-y': 'auto',
516 'overflow-x': 'hidden',
517 'margin-top': "-" + moveCalc + 'px'
521 this.$container.append(this.$ul);
525 * Build the dropdown options and binds all necessary events.
527 * Uses createDivider and createOptionValue to create the necessary options.
529 buildDropdownOptions: function() {
531 this.$select.children().each($.proxy(function(index, element) {
533 var $element = $(element);
534 // Support optgroups and options without a group simultaneously.
535 var tag = $element.prop('tagName')
538 if ($element.prop('value') === this.options.selectAllValue) {
542 if (tag === 'optgroup') {
543 this.createOptgroup(element);
545 else if (tag === 'option') {
547 if ($element.data('role') === 'divider') {
548 this.createDivider();
551 this.createOptionValue(element);
556 // Other illegal tags will be ignored.
559 // Bind the change event on the dropdown elements.
560 $('li:not(.multiselect-group) input', this.$ul).on('change', $.proxy(function(event) {
561 var $target = $(event.target);
563 var checked = $target.prop('checked') || false;
564 var isSelectAllOption = $target.val() === this.options.selectAllValue;
566 // Apply or unapply the configured selected class.
567 if (this.options.selectedClass) {
569 $target.closest('li')
570 .addClass(this.options.selectedClass);
573 $target.closest('li')
574 .removeClass(this.options.selectedClass);
578 // Get the corresponding option.
579 var value = $target.val();
580 var $option = this.getOptionByValue(value);
582 var $optionsNotThis = $('option', this.$select).not($option);
583 var $checkboxesNotThis = $('input', this.$container).not($target);
585 if (isSelectAllOption) {
588 this.selectAll(this.options.selectAllJustVisible, true);
591 this.deselectAll(this.options.selectAllJustVisible, true);
596 $option.prop('selected', true);
598 if (this.options.multiple) {
599 // Simply select additional option.
600 $option.prop('selected', true);
603 // Unselect all other options and corresponding checkboxes.
604 if (this.options.selectedClass) {
605 $($checkboxesNotThis).closest('li').removeClass(this.options.selectedClass);
608 $($checkboxesNotThis).prop('checked', false);
609 $optionsNotThis.prop('selected', false);
611 // It's a single selection, so close.
612 this.$button.click();
615 if (this.options.selectedClass === "active") {
616 $optionsNotThis.closest("a").css("outline", "");
621 $option.prop('selected', false);
624 // To prevent select all from firing onChange: #575
625 this.options.onChange($option, checked);
627 // Do not update select all or optgroups on select all change!
628 this.updateSelectAll();
630 if (this.options.enableClickableOptGroups && this.options.multiple) {
631 this.updateOptGroups();
635 this.$select.change();
636 this.updateButtonText();
638 if(this.options.preventInputChangeEvent) {
643 $('li a', this.$ul).on('mousedown', function(e) {
645 // Prevent selecting text by Shift+click
650 $('li a', this.$ul).on('touchstart click', $.proxy(function(event) {
651 event.stopPropagation();
653 var $target = $(event.target);
655 if (event.shiftKey && this.options.multiple) {
656 if($target.is("label")){ // Handles checkbox selection manually (see https://github.com/davidstutz/bootstrap-multiselect/issues/431)
657 event.preventDefault();
658 $target = $target.find("input");
659 $target.prop("checked", !$target.prop("checked"));
661 var checked = $target.prop('checked') || false;
663 if (this.lastToggledInput !== null && this.lastToggledInput !== $target) { // Make sure we actually have a range
664 var from = $target.closest("li").index();
665 var to = this.lastToggledInput.closest("li").index();
667 if (from > to) { // Swap the indices
673 // Make sure we grab all elements since slice excludes the last index
676 // Change the checkboxes and underlying options
677 var range = this.$ul.find("li").slice(from, to).find("input");
679 range.prop('checked', checked);
681 if (this.options.selectedClass) {
683 .toggleClass(this.options.selectedClass, checked);
686 for (var i = 0, j = range.length; i < j; i++) {
687 var $checkbox = $(range[i]);
689 var $option = this.getOptionByValue($checkbox.val());
691 $option.prop('selected', checked);
695 // Trigger the select "change" event
696 $target.trigger("change");
699 // Remembers last clicked option
700 if($target.is("input") && !$target.closest("li").is(".multiselect-item")){
701 this.lastToggledInput = $target;
708 this.$container.off('keydown.multiselect').on('keydown.multiselect', $.proxy(function(event) {
709 if ($('input[type="text"]', this.$container).is(':focus')) {
713 if (event.keyCode === 9 && this.$container.hasClass('open')) {
714 this.$button.click();
717 var $items = $(this.$container).find("li:not(.divider):not(.disabled) a").filter(":visible");
719 if (!$items.length) {
723 var index = $items.index($items.filter(':focus'));
726 if (event.keyCode === 38 && index > 0) {
730 else if (event.keyCode === 40 && index < $items.length - 1) {
737 var $current = $items.eq(index);
740 if (event.keyCode === 32 || event.keyCode === 13) {
741 var $checkbox = $current.find('input');
743 $checkbox.prop("checked", !$checkbox.prop("checked"));
747 event.stopPropagation();
748 event.preventDefault();
752 if (this.options.enableClickableOptGroups && this.options.multiple) {
753 $("li.multiselect-group input", this.$ul).on("change", $.proxy(function(event) {
754 event.stopPropagation();
756 var $target = $(event.target);
757 var checked = $target.prop('checked') || false;
759 var $li = $(event.target).closest('li');
760 var $group = $li.nextUntil("li.multiselect-group")
761 .not('.multiselect-filter-hidden')
764 var $inputs = $group.find("input");
769 if (this.options.selectedClass) {
771 $li.addClass(this.options.selectedClass);
774 $li.removeClass(this.options.selectedClass);
778 $.each($inputs, $.proxy(function(index, input) {
779 var value = $(input).val();
780 var $option = this.getOptionByValue(value);
783 $(input).prop('checked', true);
784 $(input).closest('li')
785 .addClass(this.options.selectedClass);
787 $option.prop('selected', true);
790 $(input).prop('checked', false);
791 $(input).closest('li')
792 .removeClass(this.options.selectedClass);
794 $option.prop('selected', false);
797 $options.push(this.getOptionByValue(value));
800 // Cannot use select or deselect here because it would call updateOptGroups again.
802 this.options.onChange($options, checked);
804 this.updateButtonText();
805 this.updateSelectAll();
809 if (this.options.enableCollapsibleOptGroups && this.options.multiple) {
810 $("li.multiselect-group .caret-container", this.$ul).on("click", $.proxy(function(event) {
811 var $li = $(event.target).closest('li');
812 var $inputs = $li.nextUntil("li.multiselect-group")
813 .not('.multiselect-filter-hidden');
816 $inputs.each(function() {
817 visible = visible && $(this).is(':visible');
822 .addClass('multiselect-collapsible-hidden');
826 .removeClass('multiselect-collapsible-hidden');
830 $("li.multiselect-all", this.$ul).css('background', '#f3f3f3').css('border-bottom', '1px solid #eaeaea');
831 $("li.multiselect-all > a > label.checkbox", this.$ul).css('padding', '3px 20px 3px 35px');
832 $("li.multiselect-group > a > input", this.$ul).css('margin', '4px 0px 5px -20px');
837 * Create an option using the given select option.
839 * @param {jQuery} element
841 createOptionValue: function(element) {
842 var $element = $(element);
843 if ($element.is(':selected')) {
844 $element.prop('selected', true);
847 // Support the label attribute on options.
848 var label = this.options.optionLabel(element);
849 var classes = this.options.optionClass(element);
850 var value = $element.val();
851 var inputType = this.options.multiple ? "checkbox" : "radio";
853 var $li = $(this.options.templates.li);
854 var $label = $('label', $li);
855 $label.addClass(inputType);
856 $li.addClass(classes);
858 if (this.options.enableHTML) {
859 $label.html(" " + label);
862 $label.text(" " + label);
865 var $checkbox = $('<input/>').attr('type', inputType);
867 var name = this.options.checkboxName($element);
869 $checkbox.attr('name', name);
872 $label.prepend($checkbox);
874 var selected = $element.prop('selected') || false;
875 $checkbox.val(value);
877 if (value === this.options.selectAllValue) {
878 $li.addClass("multiselect-item multiselect-all");
879 $checkbox.parent().parent()
880 .addClass('multiselect-all');
883 $label.attr('title', $element.attr('title'));
885 this.$ul.append($li);
887 if ($element.is(':disabled')) {
888 $checkbox.attr('disabled', 'disabled')
889 .prop('disabled', true)
891 .attr("tabindex", "-1")
893 .addClass('disabled');
896 $checkbox.prop('checked', selected);
898 if (selected && this.options.selectedClass) {
899 $checkbox.closest('li')
900 .addClass(this.options.selectedClass);
905 * Creates a divider using the given select option.
907 * @param {jQuery} element
909 createDivider: function(element) {
910 var $divider = $(this.options.templates.divider);
911 this.$ul.append($divider);
915 * Creates an optgroup.
917 * @param {jQuery} group
919 createOptgroup: function(group) {
920 var label = $(group).attr("label");
921 var value = $(group).attr("value");
922 var $li = $('<li class="multiselect-item multiselect-group"><a href="javascript:void(0);"><label><b></b></label></a></li>');
924 var classes = this.options.optionClass(group);
925 $li.addClass(classes);
927 if (this.options.enableHTML) {
928 $('label b', $li).html(" " + label);
931 $('label b', $li).text(" " + label);
934 if (this.options.enableCollapsibleOptGroups && this.options.multiple) {
935 $('a', $li).append('<span class="caret-container"><b class="caret"></b></span>');
938 if (this.options.enableClickableOptGroups && this.options.multiple) {
939 $('a label', $li).prepend('<input type="checkbox" value="' + value + '"/>');
942 if ($(group).is(':disabled')) {
943 $li.addClass('disabled');
946 this.$ul.append($li);
948 $("option", group).each($.proxy(function($, group) {
949 this.createOptionValue(group);
954 * Build the select all.
956 * Checks if a select all has already been created.
958 buildSelectAll: function() {
959 if (typeof this.options.selectAllValue === 'number') {
960 this.options.selectAllValue = this.options.selectAllValue.toString();
963 var alreadyHasSelectAll = this.hasSelectAll();
965 if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple
966 && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) {
968 // Check whether to add a divider after the select all.
969 if (this.options.includeSelectAllDivider) {
970 this.$ul.prepend($(this.options.templates.divider));
973 var $li = $(this.options.templates.li);
974 $('label', $li).addClass("checkbox");
976 if (this.options.enableHTML) {
977 $('label', $li).html(" " + this.options.selectAllText);
980 $('label', $li).text(" " + this.options.selectAllText);
983 if (this.options.selectAllName) {
984 $('label', $li).prepend('<input type="checkbox" name="' + this.options.selectAllName + '" />');
987 $('label', $li).prepend('<input type="checkbox" />');
990 var $checkbox = $('input', $li);
991 $checkbox.val(this.options.selectAllValue);
993 $li.addClass("multiselect-item multiselect-all");
994 $checkbox.parent().parent()
995 .addClass('multiselect-all');
997 this.$ul.prepend($li);
999 $checkbox.prop('checked', false);
1004 * Builds the filter.
1006 buildFilter: function() {
1008 // Build filter if filtering OR case insensitive filtering is enabled and the number of options exceeds (or equals) enableFilterLength.
1009 if (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering) {
1010 var enableFilterLength = Math.max(this.options.enableFiltering, this.options.enableCaseInsensitiveFiltering);
1012 if (this.$select.find('option').length >= enableFilterLength) {
1014 this.$filter = $(this.options.templates.filter);
1015 $('input', this.$filter).attr('placeholder', this.options.filterPlaceholder);
1017 // Adds optional filter clear button
1018 if(this.options.includeFilterClearBtn) {
1019 var clearBtn = $(this.options.templates.filterClearBtn);
1020 clearBtn.on('click', $.proxy(function(event){
1021 clearTimeout(this.searchTimeout);
1023 this.$filter.find('.multiselect-search').val('');
1024 $('li', this.$ul).show().removeClass('multiselect-filter-hidden');
1026 this.updateSelectAll();
1028 if (this.options.enableClickableOptGroups && this.options.multiple) {
1029 this.updateOptGroups();
1033 this.$filter.find('.input-group').append(clearBtn);
1036 this.$ul.prepend(this.$filter);
1038 this.$filter.val(this.query).on('click', function(event) {
1039 event.stopPropagation();
1040 }).on('input keydown', $.proxy(function(event) {
1041 // Cancel enter key default behaviour
1042 if (event.which === 13) {
1043 event.preventDefault();
1046 // This is useful to catch "keydown" events after the browser has updated the control.
1047 clearTimeout(this.searchTimeout);
1049 this.searchTimeout = this.asyncFunction($.proxy(function() {
1051 if (this.query !== event.target.value) {
1052 this.query = event.target.value;
1054 var currentGroup, currentGroupVisible;
1055 $.each($('li', this.$ul), $.proxy(function(index, element) {
1056 var value = $('input', element).length > 0 ? $('input', element).val() : "";
1057 var text = $('label', element).text();
1059 var filterCandidate = '';
1060 if ((this.options.filterBehavior === 'text')) {
1061 filterCandidate = text;
1063 else if ((this.options.filterBehavior === 'value')) {
1064 filterCandidate = value;
1066 else if (this.options.filterBehavior === 'both') {
1067 filterCandidate = text + '\n' + value;
1070 if (value !== this.options.selectAllValue && text) {
1072 // By default lets assume that element is not
1073 // interesting for this search.
1074 var showElement = false;
1076 if (this.options.enableCaseInsensitiveFiltering) {
1077 filterCandidate = filterCandidate.toLowerCase();
1078 this.query = this.query.toLowerCase();
1081 if (this.options.enableFullValueFiltering && this.options.filterBehavior !== 'both') {
1082 var valueToMatch = filterCandidate.trim().substring(0, this.query.length);
1083 if (this.query.indexOf(valueToMatch) > -1) {
1087 else if (filterCandidate.indexOf(this.query) > -1) {
1091 // Toggle current element (group or group item) according to showElement boolean.
1092 $(element).toggle(showElement)
1093 .toggleClass('multiselect-filter-hidden', !showElement);
1095 // Differentiate groups and group items.
1096 if ($(element).hasClass('multiselect-group')) {
1097 // Remember group status.
1098 currentGroup = element;
1099 currentGroupVisible = showElement;
1102 // Show group name when at least one of its items is visible.
1104 $(currentGroup).show()
1105 .removeClass('multiselect-filter-hidden');
1108 // Show all group items when group name satisfies filter.
1109 if (!showElement && currentGroupVisible) {
1111 .removeClass('multiselect-filter-hidden');
1118 this.updateSelectAll();
1120 if (this.options.enableClickableOptGroups && this.options.multiple) {
1121 this.updateOptGroups();
1124 this.options.onFiltering(event.target);
1126 }, this), 300, this);
1133 * Unbinds the whole plugin.
1135 destroy: function() {
1136 this.$container.remove();
1137 this.$select.show();
1139 // reset original state
1140 this.$select.prop('disabled', this.options.wasDisabled);
1142 this.$select.data('multiselect', null);
1146 * Refreshs the multiselect based on the selected options of the select.
1148 refresh: function () {
1149 var inputs = $.map($('li input', this.$ul), $);
1151 $('option', this.$select).each($.proxy(function (index, element) {
1152 var $elem = $(element);
1153 var value = $elem.val();
1155 for (var i = inputs.length; 0 < i--; /**/) {
1156 if (value !== ($input = inputs[i]).val())
1157 continue; // wrong li
1159 if ($elem.is(':selected')) {
1160 $input.prop('checked', true);
1162 if (this.options.selectedClass) {
1163 $input.closest('li')
1164 .addClass(this.options.selectedClass);
1168 $input.prop('checked', false);
1170 if (this.options.selectedClass) {
1171 $input.closest('li')
1172 .removeClass(this.options.selectedClass);
1176 if ($elem.is(":disabled")) {
1177 $input.attr('disabled', 'disabled')
1178 .prop('disabled', true)
1180 .addClass('disabled');
1183 $input.prop('disabled', false)
1185 .removeClass('disabled');
1187 break; // assumes unique values
1191 this.updateButtonText();
1192 this.updateSelectAll();
1194 if (this.options.enableClickableOptGroups && this.options.multiple) {
1195 this.updateOptGroups();
1200 * Select all options of the given values.
1202 * If triggerOnChange is set to true, the on change event is triggered if
1203 * and only if one value is passed.
1205 * @param {Array} selectValues
1206 * @param {Boolean} triggerOnChange
1208 select: function(selectValues, triggerOnChange) {
1209 if(!$.isArray(selectValues)) {
1210 selectValues = [selectValues];
1213 for (var i = 0; i < selectValues.length; i++) {
1214 var value = selectValues[i];
1216 if (value === null || value === undefined) {
1220 var $option = this.getOptionByValue(value);
1221 var $checkbox = this.getInputByValue(value);
1223 if($option === undefined || $checkbox === undefined) {
1227 if (!this.options.multiple) {
1228 this.deselectAll(false);
1231 if (this.options.selectedClass) {
1232 $checkbox.closest('li')
1233 .addClass(this.options.selectedClass);
1236 $checkbox.prop('checked', true);
1237 $option.prop('selected', true);
1239 if (triggerOnChange) {
1240 this.options.onChange($option, true);
1244 this.updateButtonText();
1245 this.updateSelectAll();
1247 if (this.options.enableClickableOptGroups && this.options.multiple) {
1248 this.updateOptGroups();
1253 * Clears all selected items.
1255 clearSelection: function () {
1256 this.deselectAll(false);
1257 this.updateButtonText();
1258 this.updateSelectAll();
1260 if (this.options.enableClickableOptGroups && this.options.multiple) {
1261 this.updateOptGroups();
1266 * Deselects all options of the given values.
1268 * If triggerOnChange is set to true, the on change event is triggered, if
1269 * and only if one value is passed.
1271 * @param {Array} deselectValues
1272 * @param {Boolean} triggerOnChange
1274 deselect: function(deselectValues, triggerOnChange) {
1275 if(!$.isArray(deselectValues)) {
1276 deselectValues = [deselectValues];
1279 for (var i = 0; i < deselectValues.length; i++) {
1280 var value = deselectValues[i];
1282 if (value === null || value === undefined) {
1286 var $option = this.getOptionByValue(value);
1287 var $checkbox = this.getInputByValue(value);
1289 if($option === undefined || $checkbox === undefined) {
1293 if (this.options.selectedClass) {
1294 $checkbox.closest('li')
1295 .removeClass(this.options.selectedClass);
1298 $checkbox.prop('checked', false);
1299 $option.prop('selected', false);
1301 if (triggerOnChange) {
1302 this.options.onChange($option, false);
1306 this.updateButtonText();
1307 this.updateSelectAll();
1309 if (this.options.enableClickableOptGroups && this.options.multiple) {
1310 this.updateOptGroups();
1315 * Selects all enabled & visible options.
1317 * If justVisible is true or not specified, only visible options are selected.
1319 * @param {Boolean} justVisible
1320 * @param {Boolean} triggerOnSelectAll
1322 selectAll: function (justVisible, triggerOnSelectAll) {
1324 var justVisible = typeof justVisible === 'undefined' ? true : justVisible;
1325 var allLis = $("li:not(.divider):not(.disabled):not(.multiselect-group)", this.$ul);
1326 var visibleLis = $("li:not(.divider):not(.disabled):not(.multiselect-group):not(.multiselect-filter-hidden):not(.multiselect-collapisble-hidden)", this.$ul).filter(':visible');
1329 $('input:enabled' , visibleLis).prop('checked', true);
1330 visibleLis.addClass(this.options.selectedClass);
1332 $('input:enabled' , visibleLis).each($.proxy(function(index, element) {
1333 var value = $(element).val();
1334 var option = this.getOptionByValue(value);
1335 $(option).prop('selected', true);
1339 $('input:enabled' , allLis).prop('checked', true);
1340 allLis.addClass(this.options.selectedClass);
1342 $('input:enabled' , allLis).each($.proxy(function(index, element) {
1343 var value = $(element).val();
1344 var option = this.getOptionByValue(value);
1345 $(option).prop('selected', true);
1349 $('li input[value="' + this.options.selectAllValue + '"]', this.$ul).prop('checked', true);
1351 if (this.options.enableClickableOptGroups && this.options.multiple) {
1352 this.updateOptGroups();
1355 if (triggerOnSelectAll) {
1356 this.options.onSelectAll();
1361 * Deselects all options.
1363 * If justVisible is true or not specified, only visible options are deselected.
1365 * @param {Boolean} justVisible
1367 deselectAll: function (justVisible, triggerOnDeselectAll) {
1369 var justVisible = typeof justVisible === 'undefined' ? true : justVisible;
1370 var allLis = $("li:not(.divider):not(.disabled):not(.multiselect-group)", this.$ul);
1371 var visibleLis = $("li:not(.divider):not(.disabled):not(.multiselect-group):not(.multiselect-filter-hidden):not(.multiselect-collapisble-hidden)", this.$ul).filter(':visible');
1374 $('input[type="checkbox"]:enabled' , visibleLis).prop('checked', false);
1375 visibleLis.removeClass(this.options.selectedClass);
1377 $('input[type="checkbox"]:enabled' , visibleLis).each($.proxy(function(index, element) {
1378 var value = $(element).val();
1379 var option = this.getOptionByValue(value);
1380 $(option).prop('selected', false);
1384 $('input[type="checkbox"]:enabled' , allLis).prop('checked', false);
1385 allLis.removeClass(this.options.selectedClass);
1387 $('input[type="checkbox"]:enabled' , allLis).each($.proxy(function(index, element) {
1388 var value = $(element).val();
1389 var option = this.getOptionByValue(value);
1390 $(option).prop('selected', false);
1394 $('li input[value="' + this.options.selectAllValue + '"]', this.$ul).prop('checked', false);
1396 if (this.options.enableClickableOptGroups && this.options.multiple) {
1397 this.updateOptGroups();
1400 if (triggerOnDeselectAll) {
1401 this.options.onDeselectAll();
1406 * Rebuild the plugin.
1408 * Rebuilds the dropdown, the filter and the select all option.
1410 rebuild: function() {
1413 // Important to distinguish between radios and checkboxes.
1414 this.options.multiple = this.$select.attr('multiple') === "multiple";
1416 this.buildSelectAll();
1417 this.buildDropdownOptions();
1420 this.updateButtonText();
1421 this.updateSelectAll(true);
1423 if (this.options.enableClickableOptGroups && this.options.multiple) {
1424 this.updateOptGroups();
1427 if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) {
1434 if (this.options.dropRight) {
1435 this.$ul.addClass('pull-right');
1440 * The provided data will be used to build the dropdown.
1442 dataprovider: function(dataprovider) {
1444 var groupCounter = 0;
1445 var $select = this.$select.empty();
1447 $.each(dataprovider, function (index, option) {
1450 if ($.isArray(option.children)) { // create optiongroup tag
1453 $tag = $('<optgroup/>').attr({
1454 label: option.label || 'Group ' + groupCounter,
1455 disabled: !!option.disabled
1458 forEach(option.children, function(subOption) { // add children option tags
1460 value: subOption.value,
1461 label: subOption.label || subOption.value,
1462 title: subOption.title,
1463 selected: !!subOption.selected,
1464 disabled: !!subOption.disabled
1467 //Loop through attributes object and add key-value for each attribute
1468 for (var key in subOption.attributes) {
1469 attributes['data-' + key] = subOption.attributes[key];
1471 //Append original attributes + new data attributes to option
1472 $tag.append($('<option/>').attr(attributes));
1478 'value': option.value,
1479 'label': option.label || option.value,
1480 'title': option.title,
1481 'class': option.class,
1482 'selected': !!option.selected,
1483 'disabled': !!option.disabled
1485 //Loop through attributes object and add key-value for each attribute
1486 for (var key in option.attributes) {
1487 attributes['data-' + key] = option.attributes[key];
1489 //Append original attributes + new data attributes to option
1490 $tag = $('<option/>').attr(attributes);
1492 $tag.text(option.label || option.value);
1495 $select.append($tag);
1502 * Enable the multiselect.
1504 enable: function() {
1505 this.$select.prop('disabled', false);
1506 this.$button.prop('disabled', false)
1507 .removeClass('disabled');
1511 * Disable the multiselect.
1513 disable: function() {
1514 this.$select.prop('disabled', true);
1515 this.$button.prop('disabled', true)
1516 .addClass('disabled');
1522 * @param {Array} options
1524 setOptions: function(options) {
1525 this.options = this.mergeOptions(options);
1529 * Merges the given options with the default options.
1531 * @param {Array} options
1534 mergeOptions: function(options) {
1535 return $.extend(true, {}, this.defaults, this.options, options);
1539 * Checks whether a select all checkbox is present.
1541 * @returns {Boolean}
1543 hasSelectAll: function() {
1544 return $('li.multiselect-all', this.$ul).length > 0;
1548 * Update opt groups.
1550 updateOptGroups: function() {
1551 var $groups = $('li.multiselect-group', this.$ul)
1552 var selectedClass = this.options.selectedClass;
1554 $groups.each(function() {
1555 var $options = $(this).nextUntil('li.multiselect-group')
1556 .not('.multiselect-filter-hidden')
1560 $options.each(function() {
1561 var $input = $('input', this);
1563 if (!$input.prop('checked')) {
1568 if (selectedClass) {
1570 $(this).addClass(selectedClass);
1573 $(this).removeClass(selectedClass);
1577 $('input', this).prop('checked', checked);
1582 * Updates the select all checkbox based on the currently displayed and selected checkboxes.
1584 updateSelectAll: function(notTriggerOnSelectAll) {
1585 if (this.hasSelectAll()) {
1586 var allBoxes = $("li:not(.multiselect-item):not(.multiselect-filter-hidden):not(.multiselect-group):not(.disabled) input:enabled", this.$ul);
1587 var allBoxesLength = allBoxes.length;
1588 var checkedBoxesLength = allBoxes.filter(":checked").length;
1589 var selectAllLi = $("li.multiselect-all", this.$ul);
1590 var selectAllInput = selectAllLi.find("input");
1592 if (checkedBoxesLength > 0 && checkedBoxesLength === allBoxesLength) {
1593 selectAllInput.prop("checked", true);
1594 selectAllLi.addClass(this.options.selectedClass);
1597 selectAllInput.prop("checked", false);
1598 selectAllLi.removeClass(this.options.selectedClass);
1604 * Update the button text and its title based on the currently selected options.
1606 updateButtonText: function() {
1607 var options = this.getSelected();
1609 // First update the displayed button text.
1610 if (this.options.enableHTML) {
1611 $('.multiselect .multiselect-selected-text', this.$container).html(this.options.buttonText(options, this.$select));
1614 $('.multiselect .multiselect-selected-text', this.$container).text(this.options.buttonText(options, this.$select));
1617 // Now update the title attribute of the button.
1618 $('.multiselect', this.$container).attr('title', this.options.buttonTitle(options, this.$select));
1622 * Get all selected options.
1626 getSelected: function() {
1627 return $('option', this.$select).filter(":selected");
1631 * Gets a select option by its value.
1633 * @param {String} value
1636 getOptionByValue: function (value) {
1638 var options = $('option', this.$select);
1639 var valueToCompare = value.toString();
1641 for (var i = 0; i < options.length; i = i + 1) {
1642 var option = options[i];
1643 if (option.value === valueToCompare) {
1650 * Get the input (radio/checkbox) by its value.
1652 * @param {String} value
1655 getInputByValue: function (value) {
1657 var checkboxes = $('li input:not(.multiselect-search)', this.$ul);
1658 var valueToCompare = value.toString();
1660 for (var i = 0; i < checkboxes.length; i = i + 1) {
1661 var checkbox = checkboxes[i];
1662 if (checkbox.value === valueToCompare) {
1669 * Used for knockout integration.
1671 updateOriginalOptions: function() {
1672 this.originalOptions = this.$select.clone()[0].options;
1675 asyncFunction: function(callback, timeout, self) {
1676 var args = Array.prototype.slice.call(arguments, 3);
1677 return setTimeout(function() {
1678 callback.apply(self || window, args);
1682 setAllSelectedText: function(allSelectedText) {
1683 this.options.allSelectedText = allSelectedText;
1684 this.updateButtonText();
1688 $.fn.multiselect = function(option, parameter, extraOptions) {
1689 return this.each(function() {
1690 var data = $(this).data('multiselect');
1691 var options = typeof option === 'object' && option;
1693 // Initialize the multiselect.
1695 data = new Multiselect(this, options);
1696 $(this).data('multiselect', data);
1699 // Call multiselect method.
1700 if (typeof option === 'string') {
1701 data[option](parameter, extraOptions);
1703 if (option === 'destroy') {
1704 $(this).data('multiselect', false);
1710 $.fn.multiselect.Constructor = Multiselect;
1713 $("select[data-role=multiselect]").multiselect();