From 69be623eeb1eab4d29956d7cd28564829dde49df Mon Sep 17 00:00:00 2001 From: catborise Date: Wed, 31 Oct 2018 16:51:11 +0300 Subject: [PATCH] upgrade bootstrap-multiselect to v0.9.15 --- static/css/bootstrap-multiselect.css | 39 +- static/js/bootstrap-multiselect.js | 1715 +++++++++++++++++++++----- 2 files changed, 1429 insertions(+), 325 deletions(-) diff --git a/static/css/bootstrap-multiselect.css b/static/css/bootstrap-multiselect.css index 64400cd..6a6b68a 100644 --- a/static/css/bootstrap-multiselect.css +++ b/static/css/bootstrap-multiselect.css @@ -1,38 +1 @@ - -.multiselect-container { - position: absolute; - list-style-type: none; - margin: 0; - padding: 0; -} -.multiselect-container .input-group { - margin: 5px; -} -.multiselect-container > li { - padding: 0; -} -.multiselect-container > li > a.multiselect-all label { - font-weight: bold; -} -.multiselect-container > li > label.multiselect-group { - margin: 0; - padding: 3px 20px 3px 20px; - height: 100%; -} -.multiselect-container > li > a > label { - margin: 0; - height: 100%; - cursor: pointer; - font-weight: normal; -} -.multiselect-container > li > a > label.radio, -.multiselect-container > li > a > label.checkbox { - margin: 0; -} -.multiselect-container > li > a > label > input[type="checkbox"] { - margin-bottom: 5px; -} -.btn-group > .btn-group:nth-child(2) > .multiselect.btn { - border-top-left-radius: 4px; - border-bottom-left-radius: 4px; -} +span.multiselect-native-select{position:relative}span.multiselect-native-select select{border:0!important;clip:rect(0 0 0 0)!important;height:1px!important;margin:-1px -1px -1px -3px!important;overflow:hidden!important;padding:0!important;position:absolute!important;width:1px!important;left:50%;top:30px}.multiselect-container{position:absolute;list-style-type:none;margin:0;padding:0}.multiselect-container .input-group{margin:5px}.multiselect-container .multiselect-reset .input-group{width:93%}.multiselect-container>li{padding:0}.multiselect-container>li>a.multiselect-all label{font-weight:700}.multiselect-container>li.multiselect-group label{margin:0;padding:3px 20px;height:100%;font-weight:700}.multiselect-container>li.multiselect-group-clickable label{cursor:pointer}.multiselect-container>li>a{padding:0}.multiselect-container>li>a>label{margin:0;height:100%;cursor:pointer;font-weight:400;padding:3px 20px 3px 40px}.multiselect-container>li>a>label.checkbox,.multiselect-container>li>a>label.radio{margin:0}.multiselect-container>li>a>label>input[type=checkbox]{margin-bottom:5px}.btn-group>.btn-group:nth-child(2)>.multiselect.btn{border-top-left-radius:4px;border-bottom-left-radius:4px}.form-inline .multiselect-container label.checkbox,.form-inline .multiselect-container label.radio{padding:3px 20px 3px 40px}.form-inline .multiselect-container li a label.checkbox input[type=checkbox],.form-inline .multiselect-container li a label.radio input[type=radio]{margin-left:-20px;margin-right:0} \ No newline at end of file diff --git a/static/js/bootstrap-multiselect.js b/static/js/bootstrap-multiselect.js index 0ba6569..ab1e2d6 100644 --- a/static/js/bootstrap-multiselect.js +++ b/static/js/bootstrap-multiselect.js @@ -1,148 +1,493 @@ /** - * bootstrap-multiselect.js - * https://github.com/davidstutz/bootstrap-multiselect + * Bootstrap Multiselect (http://davidstutz.de/bootstrap-multiselect/) * - * Copyright 2012, 2013 David Stutz - * - * Dual licensed under the BSD-3-Clause and the Apache License, Version 2.0. - * See the README. + * Apache License, Version 2.0: + * Copyright (c) 2012 - 2018 David Stutz + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a + * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * BSD 3-Clause License: + * Copyright (c) 2012 - 2018 David Stutz + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * - Neither the name of David Stutz nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -!function($) { - +(function (root, factory) { + // check to see if 'knockout' AMD module is specified if using requirejs + if (typeof define === 'function' && define.amd && + typeof require === 'function' && typeof require.specified === 'function' && require.specified('knockout')) { + + // AMD. Register as an anonymous module. + define(['jquery', 'knockout'], factory); + } else { + // Browser globals + factory(root.jQuery, root.ko); + } +})(this, function ($, ko) { "use strict";// jshint ;_; - if (typeof ko != 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) { + if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) { ko.bindingHandlers.multiselect = { - init : function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {}, - update : function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { - var ms = $(element).data('multiselect'); - if (!ms) { - $(element).multiselect(ko.utils.unwrapObservable(valueAccessor())); + after: ['options', 'value', 'selectedOptions', 'enable', 'disable'], + + init: function(element, valueAccessor, allBindings, viewModel, bindingContext) { + var $element = $(element); + var config = ko.toJS(valueAccessor()); + + $element.multiselect(config); + + if (allBindings.has('options')) { + var options = allBindings.get('options'); + if (ko.isObservable(options)) { + ko.computed({ + read: function() { + options(); + setTimeout(function() { + var ms = $element.data('multiselect'); + if (ms) + ms.updateOriginalOptions();//Not sure how beneficial this is. + $element.multiselect('rebuild'); + }, 1); + }, + disposeWhenNodeIsRemoved: element + }); + } } - else if (allBindingsAccessor().options && allBindingsAccessor().options().length !== ms.originalOptions.length) { - ms.updateOriginalOptions(); - $(element).multiselect('rebuild'); + + //value and selectedOptions are two-way, so these will be triggered even by our own actions. + //It needs some way to tell if they are triggered because of us or because of outside change. + //It doesn't loop but it's a waste of processing. + if (allBindings.has('value')) { + var value = allBindings.get('value'); + if (ko.isObservable(value)) { + ko.computed({ + read: function() { + value(); + setTimeout(function() { + $element.multiselect('refresh'); + }, 1); + }, + disposeWhenNodeIsRemoved: element + }).extend({ rateLimit: 100, notifyWhenChangesStop: true }); + } } + + //Switched from arrayChange subscription to general subscription using 'refresh'. + //Not sure performance is any better using 'select' and 'deselect'. + if (allBindings.has('selectedOptions')) { + var selectedOptions = allBindings.get('selectedOptions'); + if (ko.isObservable(selectedOptions)) { + ko.computed({ + read: function() { + selectedOptions(); + setTimeout(function() { + $element.multiselect('refresh'); + }, 1); + }, + disposeWhenNodeIsRemoved: element + }).extend({ rateLimit: 100, notifyWhenChangesStop: true }); + } + } + + var setEnabled = function (enable) { + setTimeout(function () { + if (enable) + $element.multiselect('enable'); + else + $element.multiselect('disable'); + }); + }; + + if (allBindings.has('enable')) { + var enable = allBindings.get('enable'); + if (ko.isObservable(enable)) { + ko.computed({ + read: function () { + setEnabled(enable()); + }, + disposeWhenNodeIsRemoved: element + }).extend({ rateLimit: 100, notifyWhenChangesStop: true }); + } else { + setEnabled(enable); + } + } + + if (allBindings.has('disable')) { + var disable = allBindings.get('disable'); + if (ko.isObservable(disable)) { + ko.computed({ + read: function () { + setEnabled(!disable()); + }, + disposeWhenNodeIsRemoved: element + }).extend({ rateLimit: 100, notifyWhenChangesStop: true }); + } else { + setEnabled(!disable); + } + } + + ko.utils.domNodeDisposal.addDisposeCallback(element, function() { + $element.multiselect('destroy'); + }); + }, + + update: function(element, valueAccessor, allBindings, viewModel, bindingContext) { + var $element = $(element); + var config = ko.toJS(valueAccessor()); + + $element.multiselect('setOptions', config); + $element.multiselect('rebuild'); } }; } + function forEach(array, callback) { + for (var index = 0; index < array.length; ++index) { + callback(array[index], index); + } + } + + /** + * Constructor to create a new multiselect using the given select. + * + * @param {jQuery} select + * @param {Object} options + * @returns {Multiselect} + */ function Multiselect(select, options) { - this.options = this.mergeOptions(options); this.$select = $(select); - + this.options = this.mergeOptions($.extend({}, options, this.$select.data())); + + // Placeholder via data attributes + if (this.$select.attr("data-placeholder")) { + this.options.nonSelectedText = this.$select.data("placeholder"); + } + // Initialization. // We have to clone to create a new reference. this.originalOptions = this.$select.clone()[0].options; this.query = ''; this.searchTimeout = null; + this.lastToggledInput = null; - this.options.multiple = this.$select.attr('multiple') == "multiple"; + this.options.multiple = this.$select.attr('multiple') === "multiple"; this.options.onChange = $.proxy(this.options.onChange, this); - + this.options.onSelectAll = $.proxy(this.options.onSelectAll, this); + this.options.onDeselectAll = $.proxy(this.options.onDeselectAll, this); + this.options.onDropdownShow = $.proxy(this.options.onDropdownShow, this); + this.options.onDropdownHide = $.proxy(this.options.onDropdownHide, this); + this.options.onDropdownShown = $.proxy(this.options.onDropdownShown, this); + this.options.onDropdownHidden = $.proxy(this.options.onDropdownHidden, this); + this.options.onInitialized = $.proxy(this.options.onInitialized, this); + this.options.onFiltering = $.proxy(this.options.onFiltering, this); + // Build select all if enabled. this.buildContainer(); this.buildButton(); - this.buildSelectAll(); this.buildDropdown(); + this.buildReset(); + this.buildSelectAll(); this.buildDropdownOptions(); this.buildFilter(); - this.updateButtonText(); - this.$select.hide().after(this.$container); - }; + this.updateButtonText(); + this.updateSelectAll(true); + + if (this.options.enableClickableOptGroups && this.options.multiple) { + this.updateOptGroups(); + } + + this.options.wasDisabled = this.$select.prop('disabled'); + if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) { + this.disable(); + } + + this.$select.wrap('').after(this.$container); + this.options.onInitialized(this.$select, this.$container); + } Multiselect.prototype = { - - // Default options. + defaults: { - // Default text function will either print 'None selected' in case no - // option is selected, or a list of the selected options up to a length of 3 selected options. - // If more than 3 options are selected, the number of selected options is printed. + /** + * Default text function will either print 'None selected' in case no + * option is selected or a list of the selected options up to a length + * of 3 selected options. + * + * @param {jQuery} options + * @param {jQuery} select + * @returns {String} + */ buttonText: function(options, select) { - if (options.length == 0) { - return this.nonSelectedText + ' '; + if (this.disabledText.length > 0 + && (select.prop('disabled') || (options.length == 0 && this.disableIfEmpty))) { + + return this.disabledText; } - else { - if (options.length > 3) { - return options.length + ' ' + this.nSelectedText + ' '; + else if (options.length === 0) { + return this.nonSelectedText; + } + else if (this.allSelectedText + && options.length === $('option', $(select)).length + && $('option', $(select)).length !== 1 + && this.multiple) { + + if (this.selectAllNumber) { + return this.allSelectedText + ' (' + options.length + ')'; } else { - var selected = ''; - options.each(function() { - var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html(); - - selected += label + ', '; - }); - return selected.substr(0, selected.length - 2) + ' '; + return this.allSelectedText; } } + else if (this.numberDisplayed != 0 && options.length > this.numberDisplayed) { + return options.length + ' ' + this.nSelectedText; + } + else { + var selected = ''; + var delimiter = this.delimiterText; + + options.each(function() { + var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text(); + selected += label + delimiter; + }); + + return selected.substr(0, selected.length - this.delimiterText.length); + } }, - // Like the buttonText option to update the title of the button. + /** + * Updates the title of the button similar to the buttonText function. + * + * @param {jQuery} options + * @param {jQuery} select + * @returns {@exp;selected@call;substr} + */ buttonTitle: function(options, select) { - var selected = ''; - options.each(function () { - selected += $(this).text() + ', '; - }); - return selected.substr(0, selected.length - 2); + if (options.length === 0) { + return this.nonSelectedText; + } + else { + var selected = ''; + var delimiter = this.delimiterText; + + options.each(function () { + var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text(); + selected += label + delimiter; + }); + return selected.substr(0, selected.length - this.delimiterText.length); + } }, - // Is triggered on change of the selected options. + checkboxName: function(option) { + return false; // no checkbox name + }, + /** + * Create a label. + * + * @param {jQuery} element + * @returns {String} + */ + optionLabel: function(element){ + return $(element).attr('label') || $(element).text(); + }, + /** + * Create a class. + * + * @param {jQuery} element + * @returns {String} + */ + optionClass: function(element) { + return $(element).attr('class') || ''; + }, + /** + * Triggered on change of the multiselect. + * + * Not triggered when selecting/deselecting options manually. + * + * @param {jQuery} option + * @param {Boolean} checked + */ onChange : function(option, checked) { }, - buttonClass: 'btn', - dropRight: false, - selectedClass: 'active', + /** + * Triggered when the dropdown is shown. + * + * @param {jQuery} event + */ + onDropdownShow: function(event) { + + }, + /** + * Triggered when the dropdown is hidden. + * + * @param {jQuery} event + */ + onDropdownHide: function(event) { + + }, + /** + * Triggered after the dropdown is shown. + * + * @param {jQuery} event + */ + onDropdownShown: function(event) { + + }, + /** + * Triggered after the dropdown is hidden. + * + * @param {jQuery} event + */ + onDropdownHidden: function(event) { + + }, + /** + * Triggered on select all. + */ + onSelectAll: function() { + + }, + /** + * Triggered on deselect all. + */ + onDeselectAll: function() { + + }, + /** + * Triggered after initializing. + * + * @param {jQuery} $select + * @param {jQuery} $container + */ + onInitialized: function($select, $container) { + + }, + /** + * Triggered on filtering. + * + * @param {jQuery} $filter + */ + onFiltering: function($filter) { + + }, + enableHTML: false, + buttonClass: 'btn btn-default', + inheritClass: false, buttonWidth: 'auto', buttonContainer: '
', + dropRight: false, + dropUp: false, + selectedClass: 'active', // Maximum height of the dropdown menu. // If maximum height is exceeded a scrollbar will be displayed. maxHeight: false, includeSelectAllOption: false, + includeSelectAllIfMoreThan: 0, selectAllText: ' Select all', selectAllValue: 'multiselect-all', + selectAllName: false, + selectAllNumber: true, + selectAllJustVisible: true, enableFiltering: false, enableCaseInsensitiveFiltering: false, + enableFullValueFiltering: false, + enableClickableOptGroups: false, + enableCollapsibleOptGroups: false, + collapseOptGroupsByDefault: false, filterPlaceholder: 'Search', // possible options: 'text', 'value', 'both' filterBehavior: 'text', + includeFilterClearBtn: true, preventInputChangeEvent: false, nonSelectedText: 'None selected', - nSelectedText: 'selected' + nSelectedText: 'selected', + allSelectedText: 'All selected', + numberDisplayed: 3, + disableIfEmpty: false, + disabledText: '', + delimiterText: ', ', + includeResetOption: false, + includeResetDivider: false, + resetText: 'Reset', + templates: { + button: '', + ul: '', + filter: '
  • ', + filterClearBtn: '', + li: '
  • ', + divider: '
  • ', + liGroup: '
  • ', + resetButton: '
  • ' + } }, - - // Templates. - templates: { - button: '', - ul: '', - filter: '
    ', - li: '
  • ', - liGroup: '
  • ' - }, - + constructor: Multiselect, - + + /** + * Builds the container of the multiselect. + */ buildContainer: function() { this.$container = $(this.options.buttonContainer); + this.$container.on('show.bs.dropdown', this.options.onDropdownShow); + this.$container.on('hide.bs.dropdown', this.options.onDropdownHide); + this.$container.on('shown.bs.dropdown', this.options.onDropdownShown); + this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden); }, - + + /** + * Builds the button of the multiselect. + */ buildButton: function() { - // Build button. - this.$button = $(this.templates.button).addClass(this.options.buttonClass); - + this.$button = $(this.options.templates.button).addClass(this.options.buttonClass); + if (this.$select.attr('class') && this.options.inheritClass) { + this.$button.addClass(this.$select.attr('class')); + } // Adopt active state. - if (this.$select.attr('disabled') == undefined) { - this.$button.removeClass('disabled'); + if (this.$select.prop('disabled')) { + this.disable(); } else { - this.$button.addClass('disabled'); + this.enable(); } - + // Manually add button width if set. - if (this.options.buttonWidth) { + if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') { this.$button.css({ - 'width' : this.options.buttonWidth + 'width' : '100%', //this.options.buttonWidth, + 'overflow' : 'hidden', + 'text-overflow' : 'ellipsis' + }); + this.$container.css({ + 'width': this.options.buttonWidth }); } @@ -151,20 +496,22 @@ if (tabindex) { this.$button.attr('tabindex', tabindex); } - - this.$container.prepend(this.$button) + + this.$container.prepend(this.$button); }, - - // Build dropdown container ul. + + /** + * Builds the ul representing the dropdown menu. + */ buildDropdown: function() { - + // Build ul. - this.$ul = $(this.templates.ul); - + this.$ul = $(this.options.templates.ul); + if (this.options.dropRight) { this.$ul.addClass('pull-right'); } - + // Set max height of dropdown menu to activate auto scrollbar. if (this.options.maxHeight) { // TODO: Add a class for this option to move the css declarations. @@ -174,108 +521,218 @@ 'overflow-x': 'hidden' }); } - - this.$container.append(this.$ul) + + if (this.options.dropUp) { + + 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)); + var moveCalc = height + 34; + + this.$ul.css({ + 'max-height': height + 'px', + 'overflow-y': 'auto', + 'overflow-x': 'hidden', + 'margin-top': "-" + moveCalc + 'px' + }); + } + + this.$container.append(this.$ul); }, - - // Build the dropdown and bind event handling. + + /** + * Build the dropdown options and binds all necessary events. + * + * Uses createDivider and createOptionValue to create the necessary options. + */ buildDropdownOptions: function() { - + this.$select.children().each($.proxy(function(index, element) { + + var $element = $(element); // Support optgroups and options without a group simultaneously. - var tag = $(element).prop('tagName').toLowerCase(); - if (tag == 'optgroup') { + var tag = $element.prop('tagName') + .toLowerCase(); + + if ($element.prop('value') === this.options.selectAllValue) { + return; + } + + if (tag === 'optgroup') { this.createOptgroup(element); } - else if (tag == 'option') { - this.createOptionValue(element); + else if (tag === 'option') { + + if ($element.data('role') === 'divider') { + this.createDivider(); + } + else { + this.createOptionValue(element); + } + } + // Other illegal tags will be ignored. }, this)); // Bind the change event on the dropdown elements. - $('li input', this.$ul).on('change', $.proxy(function(event) { - var checked = $(event.target).prop('checked') || false; - var isSelectAllOption = $(event.target).val() == this.options.selectAllValue; + $(this.$ul).off('change', 'li:not(.multiselect-group) input[type="checkbox"], li:not(.multiselect-group) input[type="radio"]'); + $(this.$ul).on('change', 'li:not(.multiselect-group) input[type="checkbox"], li:not(.multiselect-group) input[type="radio"]', $.proxy(function(event) { + var $target = $(event.target); + + var checked = $target.prop('checked') || false; + var isSelectAllOption = $target.val() === this.options.selectAllValue; // Apply or unapply the configured selected class. if (this.options.selectedClass) { if (checked) { - $(event.target).parents('li').addClass(this.options.selectedClass); + $target.closest('li') + .addClass(this.options.selectedClass); } else { - $(event.target).parents('li').removeClass(this.options.selectedClass); + $target.closest('li') + .removeClass(this.options.selectedClass); } } - + // Get the corresponding option. - var value = $(event.target).val(); + var value = $target.val(); var $option = this.getOptionByValue(value); var $optionsNotThis = $('option', this.$select).not($option); - var $checkboxesNotThis = $('input', this.$container).not($(event.target)); + var $checkboxesNotThis = $('input', this.$container).not($target); - // Toggle all options if the select all option was changed. if (isSelectAllOption) { - $checkboxesNotThis.filter(function() { - return $(this).is(':checked') != checked; - }).trigger('click'); - } - if (checked) { - $option.prop('selected', true); - - if (this.options.multiple) { - // Simply select additional option. - $option.attr('selected', 'selected'); + if (checked) { + this.selectAll(this.options.selectAllJustVisible, true); } else { - // Unselect all other options and corresponding checkboxes. - if (this.options.selectedClass) { - $($checkboxesNotThis).parents('li').removeClass(this.options.selectedClass); - } - - $($checkboxesNotThis).prop('checked', false); - $optionsNotThis.removeAttr('selected').prop('selected', false); - - // It's a single selection, so close. - this.$button.click(); - } - - if (this.options.selectedClass == "active") { - $optionsNotThis.parents("a").css("outline", ""); + this.deselectAll(this.options.selectAllJustVisible, true); } } else { - // Unselect option. - $option.removeAttr('selected').prop('selected', false); + if (checked) { + $option.prop('selected', true); + + if (this.options.multiple) { + // Simply select additional option. + $option.prop('selected', true); + } + else { + // Unselect all other options and corresponding checkboxes. + if (this.options.selectedClass) { + $($checkboxesNotThis).closest('li').removeClass(this.options.selectedClass); + } + + $($checkboxesNotThis).prop('checked', false); + $optionsNotThis.prop('selected', false); + + // It's a single selection, so close. + this.$button.click(); + } + + if (this.options.selectedClass === "active") { + $optionsNotThis.closest("a").css("outline", ""); + } + } + else { + // Unselect option. + $option.prop('selected', false); + } + + // To prevent select all from firing onChange: #575 + this.options.onChange($option, checked); + + // Do not update select all or optgroups on select all change! + this.updateSelectAll(); + + if (this.options.enableClickableOptGroups && this.options.multiple) { + this.updateOptGroups(); + } } - this.updateButtonText(); - this.options.onChange($option, checked); this.$select.change(); + this.updateButtonText(); if(this.options.preventInputChangeEvent) { return false; } }, this)); - $('li a', this.$ul).on('touchstart click', function(event) { - event.stopPropagation(); - $(event.target).blur(); + $('li a', this.$ul).on('mousedown', function(e) { + if (e.shiftKey) { + // Prevent selecting text by Shift+click + return false; + } }); + $(this.$ul).on('touchstart click', 'li a', $.proxy(function(event) { + event.stopPropagation(); + + var $target = $(event.target); + + if (event.shiftKey && this.options.multiple) { + if($target.is("label")){ // Handles checkbox selection manually (see https://github.com/davidstutz/bootstrap-multiselect/issues/431) + event.preventDefault(); + $target = $target.find("input"); + $target.prop("checked", !$target.prop("checked")); + } + var checked = $target.prop('checked') || false; + + if (this.lastToggledInput !== null && this.lastToggledInput !== $target) { // Make sure we actually have a range + var from = this.$ul.find("li:visible").index($target.parents("li")); + var to = this.$ul.find("li:visible").index(this.lastToggledInput.parents("li")); + + if (from > to) { // Swap the indices + var tmp = to; + to = from; + from = tmp; + } + + // Make sure we grab all elements since slice excludes the last index + ++to; + + // Change the checkboxes and underlying options + var range = this.$ul.find("li").not(".multiselect-filter-hidden").slice(from, to).find("input"); + + range.prop('checked', checked); + + if (this.options.selectedClass) { + range.closest('li') + .toggleClass(this.options.selectedClass, checked); + } + + for (var i = 0, j = range.length; i < j; i++) { + var $checkbox = $(range[i]); + + var $option = this.getOptionByValue($checkbox.val()); + + $option.prop('selected', checked); + } + } + + // Trigger the select "change" event + $target.trigger("change"); + } + + // Remembers last clicked option + if($target.is("input") && !$target.closest("li").is(".multiselect-item")){ + this.lastToggledInput = $target; + } + + $target.blur(); + }, this)); + // Keyboard support. - this.$container.on('keydown', $.proxy(function(event) { + this.$container.off('keydown.multiselect').on('keydown.multiselect', $.proxy(function(event) { if ($('input[type="text"]', this.$container).is(':focus')) { return; } - if ((event.keyCode == 9 || event.keyCode == 27) && this.$container.hasClass('open')) { - // Close on tab or escape. + + if (event.keyCode === 9 && this.$container.hasClass('open')) { this.$button.click(); } else { - var $items = $(this.$container).find("li:not(.divider):visible a"); + var $items = $(this.$container).find("li:not(.divider):not(.disabled) a").filter(":visible"); if (!$items.length) { return; @@ -284,11 +741,11 @@ var index = $items.index($items.filter(':focus')); // Navigation up. - if (event.keyCode == 38 && index > 0) { + if (event.keyCode === 38 && index > 0) { index--; } // Navigate down. - else if (event.keyCode == 40 && index < $items.length - 1) { + else if (event.keyCode === 40 && index < $items.length - 1) { index++; } else if (!~index) { @@ -298,7 +755,7 @@ var $current = $items.eq(index); $current.focus(); - if (event.keyCode == 32 || event.keyCode == 13) { + if (event.keyCode === 32 || event.keyCode === 13) { var $checkbox = $current.find('input'); $checkbox.prop("checked", !$checkbox.prop("checked")); @@ -309,294 +766,968 @@ event.preventDefault(); } }, this)); + + if (this.options.enableClickableOptGroups && this.options.multiple) { + $("li.multiselect-group input", this.$ul).on("change", $.proxy(function(event) { + event.stopPropagation(); + + var $target = $(event.target); + var checked = $target.prop('checked') || false; + + var $li = $(event.target).closest('li'); + var $group = $li.nextUntil("li.multiselect-group") + .not('.multiselect-filter-hidden') + .not('.disabled'); + + var $inputs = $group.find("input"); + + var values = []; + var $options = []; + + if (this.options.selectedClass) { + if (checked) { + $li.addClass(this.options.selectedClass); + } + else { + $li.removeClass(this.options.selectedClass); + } + } + + $.each($inputs, $.proxy(function(index, input) { + var value = $(input).val(); + var $option = this.getOptionByValue(value); + + if (checked) { + $(input).prop('checked', true); + $(input).closest('li') + .addClass(this.options.selectedClass); + + $option.prop('selected', true); + } + else { + $(input).prop('checked', false); + $(input).closest('li') + .removeClass(this.options.selectedClass); + + $option.prop('selected', false); + } + + $options.push(this.getOptionByValue(value)); + }, this)) + + // Cannot use select or deselect here because it would call updateOptGroups again. + + this.options.onChange($options, checked); + + this.$select.change(); + this.updateButtonText(); + this.updateSelectAll(); + }, this)); + } + + if (this.options.enableCollapsibleOptGroups && this.options.multiple) { + $("li.multiselect-group .caret-container", this.$ul).on("click", $.proxy(function(event) { + var $li = $(event.target).closest('li'); + var $inputs = $li.nextUntil("li.multiselect-group") + .not('.multiselect-filter-hidden'); + + var visible = true; + $inputs.each(function() { + visible = visible && !$(this).hasClass('multiselect-collapsible-hidden'); + }); + + if (visible) { + $inputs.hide() + .addClass('multiselect-collapsible-hidden'); + } + else { + $inputs.show() + .removeClass('multiselect-collapsible-hidden'); + } + }, this)); + + $("li.multiselect-all", this.$ul).css('background', '#f3f3f3').css('border-bottom', '1px solid #eaeaea'); + $("li.multiselect-all > a > label.checkbox", this.$ul).css('padding', '3px 20px 3px 35px'); + $("li.multiselect-group > a > input", this.$ul).css('margin', '4px 0px 5px -20px'); + } }, - - // Will build an dropdown element for the given option. + + /** + * Create an option using the given select option. + * + * @param {jQuery} element + */ createOptionValue: function(element) { - if ($(element).is(':selected')) { - $(element).attr('selected', 'selected').prop('selected', true); + var $element = $(element); + if ($element.is(':selected')) { + $element.prop('selected', true); } // Support the label attribute on options. - var label = $(element).attr('label') || $(element).html(); - var value = $(element).val(); + var label = this.options.optionLabel(element); + var classes = this.options.optionClass(element); + var value = $element.val(); var inputType = this.options.multiple ? "checkbox" : "radio"; - var $li = $(this.templates.li); - $('label', $li).addClass(inputType); - $('input', $li).attr('type', inputType); + var $li = $(this.options.templates.li); + var $label = $('label', $li); + $label.addClass(inputType); + $label.attr("title", label); + $li.addClass(classes); - var selected = $(element).prop('selected') || false; - var $checkbox = $('input', $li); - $checkbox.val(value); - - if (value == this.options.selectAllValue) { - $checkbox.parent().parent().addClass('multiselect-all'); + // Hide all children items when collapseOptGroupsByDefault is true + if (this.options.collapseOptGroupsByDefault && $(element).parent().prop("tagName").toLowerCase() === "optgroup") { + $li.addClass("multiselect-collapsible-hidden"); + $li.hide(); } - $('label', $li).append(" " + label); + if (this.options.enableHTML) { + $label.html(" " + label); + } + else { + $label.text(" " + label); + } + + var $checkbox = $('').attr('type', inputType); + + var name = this.options.checkboxName($element); + if (name) { + $checkbox.attr('name', name); + } + + $label.prepend($checkbox); + + var selected = $element.prop('selected') || false; + $checkbox.val(value); + + if (value === this.options.selectAllValue) { + $li.addClass("multiselect-item multiselect-all"); + $checkbox.parent().parent() + .addClass('multiselect-all'); + } + + $label.attr('title', $element.attr('title')); this.$ul.append($li); - if ($(element).is(':disabled')) { - $checkbox.attr('disabled', 'disabled').prop('disabled', true).parents('li').addClass('disabled'); + if ($element.is(':disabled')) { + $checkbox.attr('disabled', 'disabled') + .prop('disabled', true) + .closest('a') + .attr("tabindex", "-1") + .closest('li') + .addClass('disabled'); } $checkbox.prop('checked', selected); if (selected && this.options.selectedClass) { - $checkbox.parents('li').addClass(this.options.selectedClass); + $checkbox.closest('li') + .addClass(this.options.selectedClass); } }, - // Create optgroup. - createOptgroup: function(group) { - var groupName = $(group).prop('label'); + /** + * Creates a divider using the given select option. + * + * @param {jQuery} element + */ + createDivider: function(element) { + var $divider = $(this.options.templates.divider); + this.$ul.append($divider); + }, + + /** + * Creates an optgroup. + * + * @param {jQuery} group + */ + createOptgroup: function(group) { + var label = $(group).attr("label"); + var value = $(group).attr("value"); + var $li = $('
  • '); + + var classes = this.options.optionClass(group); + $li.addClass(classes); + + if (this.options.enableHTML) { + $('label b', $li).html(" " + label); + } + else { + $('label b', $li).text(" " + label); + } + + if (this.options.enableCollapsibleOptGroups && this.options.multiple) { + $('a', $li).append(''); + } + + if (this.options.enableClickableOptGroups && this.options.multiple) { + $('a label', $li).prepend(''); + } + + if ($(group).is(':disabled')) { + $li.addClass('disabled'); + } - // Add a header for the group. - var $li = $(this.templates.liGroup); - $('label', $li).text(groupName); - this.$ul.append($li); - // Add the options of the group. - $('option', group).each($.proxy(function(index, element) { - this.createOptionValue(element); - }, this)); + $("option", group).each($.proxy(function($, group) { + this.createOptionValue(group); + }, this)) }, - - // Add the select all option to the select. - buildSelectAll: function() { - var alreadyHasSelectAll = this.$select[0][0] ? this.$select[0][0].value == this.options.selectAllValue : false; - console.log(this.options); - // If options.includeSelectAllOption === true, add the include all checkbox. - if (this.options.includeSelectAllOption && this.options.multiple && !alreadyHasSelectAll) { - this.$select.prepend(''); + + /** + * Build the reset. + * + */ + buildReset: function() { + if (this.options.includeResetOption) { + + // Check whether to add a divider after the reset. + if (this.options.includeResetDivider) { + this.$ul.prepend($(this.options.templates.divider)); + } + + var $resetButton = $(this.options.templates.resetButton); + + if (this.options.enableHTML) { + $('a', $resetButton).html(this.options.resetText); + } + else { + $('a', $resetButton).text(this.options.resetText); + } + + $('a', $resetButton).click($.proxy(function(){ + this.clearSelection(); + }, this)); + + this.$ul.prepend($resetButton); } }, - - // Build and bind filter. + + /** + * Build the select all. + * + * Checks if a select all has already been created. + */ + buildSelectAll: function() { + if (typeof this.options.selectAllValue === 'number') { + this.options.selectAllValue = this.options.selectAllValue.toString(); + } + + var alreadyHasSelectAll = this.hasSelectAll(); + + if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple + && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) { + + // Check whether to add a divider after the select all. + if (this.options.includeSelectAllDivider) { + this.$ul.prepend($(this.options.templates.divider)); + } + + var $li = $(this.options.templates.li); + $('label', $li).addClass("checkbox"); + + if (this.options.enableHTML) { + $('label', $li).html(" " + this.options.selectAllText); + } + else { + $('label', $li).text(" " + this.options.selectAllText); + } + + if (this.options.selectAllName) { + $('label', $li).prepend(''); + } + else { + $('label', $li).prepend(''); + } + + var $checkbox = $('input', $li); + $checkbox.val(this.options.selectAllValue); + + $li.addClass("multiselect-item multiselect-all"); + $checkbox.parent().parent() + .addClass('multiselect-all'); + + this.$ul.prepend($li); + + $checkbox.prop('checked', false); + } + }, + + /** + * Builds the filter. + */ buildFilter: function() { - + // Build filter if filtering OR case insensitive filtering is enabled and the number of options exceeds (or equals) enableFilterLength. if (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering) { var enableFilterLength = Math.max(this.options.enableFiltering, this.options.enableCaseInsensitiveFiltering); + if (this.$select.find('option').length >= enableFilterLength) { - - this.$filter = $(this.templates.filter).attr('placeholder', this.options.filterPlaceholder); + + this.$filter = $(this.options.templates.filter); + $('input', this.$filter).attr('placeholder', this.options.filterPlaceholder); + + // Adds optional filter clear button + if(this.options.includeFilterClearBtn) { + var clearBtn = $(this.options.templates.filterClearBtn); + clearBtn.on('click', $.proxy(function(event){ + clearTimeout(this.searchTimeout); + + this.query = ''; + this.$filter.find('.multiselect-search').val(''); + $('li', this.$ul).show().removeClass('multiselect-filter-hidden'); + + this.updateSelectAll(); + + if (this.options.enableClickableOptGroups && this.options.multiple) { + this.updateOptGroups(); + } + + }, this)); + this.$filter.find('.input-group').append(clearBtn); + } + this.$ul.prepend(this.$filter); this.$filter.val(this.query).on('click', function(event) { event.stopPropagation(); - }).on('keydown', $.proxy(function(event) { + }).on('input keydown', $.proxy(function(event) { + // Cancel enter key default behaviour + if (event.which === 13) { + event.preventDefault(); + } + // This is useful to catch "keydown" events after the browser has updated the control. clearTimeout(this.searchTimeout); this.searchTimeout = this.asyncFunction($.proxy(function() { - if (this.query != event.target.value) { + if (this.query !== event.target.value) { this.query = event.target.value; + var currentGroup, currentGroupVisible; $.each($('li', this.$ul), $.proxy(function(index, element) { - var value = $('input', element).val(); - if (value != this.options.selectAllValue) { - var text = $('label', element).text(); - var value = $('input', element).val(); - if (value && text && value != this.options.selectAllValue) { - // by default lets assume that element is not - // interesting for this search - var showElement = false; + var value = $('input', element).length > 0 ? $('input', element).val() : ""; + var text = $('label', element).text(); - var filterCandidate = ''; - if ((this.options.filterBehavior == 'text' || this.options.filterBehavior == 'both')) { - filterCandidate = text; - } - if ((this.options.filterBehavior == 'value' || this.options.filterBehavior == 'both')) { - filterCandidate = value; - } + var filterCandidate = ''; + if ((this.options.filterBehavior === 'text')) { + filterCandidate = text; + } + else if ((this.options.filterBehavior === 'value')) { + filterCandidate = value; + } + else if (this.options.filterBehavior === 'both') { + filterCandidate = text + '\n' + value; + } - if (this.options.enableCaseInsensitiveFiltering && filterCandidate.toLowerCase().indexOf(this.query.toLowerCase()) > -1) { - showElement = true; - } - else if (filterCandidate.indexOf(this.query) > -1) { + if (value !== this.options.selectAllValue && text) { + + // By default lets assume that element is not + // interesting for this search. + var showElement = false; + + if (this.options.enableCaseInsensitiveFiltering) { + filterCandidate = filterCandidate.toLowerCase(); + this.query = this.query.toLowerCase(); + } + + if (this.options.enableFullValueFiltering && this.options.filterBehavior !== 'both') { + var valueToMatch = filterCandidate.trim().substring(0, this.query.length); + if (this.query.indexOf(valueToMatch) > -1) { showElement = true; } + } + else if (filterCandidate.indexOf(this.query) > -1) { + showElement = true; + } + // Toggle current element (group or group item) according to showElement boolean. + if(!showElement){ + $(element).css('display', 'none'); + $(element).addClass('multiselect-filter-hidden'); + } + if(showElement){ + $(element).css('display', 'block'); + $(element).removeClass('multiselect-filter-hidden'); + } + + // Differentiate groups and group items. + if ($(element).hasClass('multiselect-group')) { + // Remember group status. + currentGroup = element; + currentGroupVisible = showElement; + } + else { + // Show group name when at least one of its items is visible. if (showElement) { - $(element).show(); + $(currentGroup).show() + .removeClass('multiselect-filter-hidden'); } - else { - $(element).hide(); + + // Show all group items when group name satisfies filter. + if (!showElement && currentGroupVisible) { + $(element).show() + .removeClass('multiselect-filter-hidden'); } } } }, this)); } + + this.updateSelectAll(); + + if (this.options.enableClickableOptGroups && this.options.multiple) { + this.updateOptGroups(); + } + + this.options.onFiltering(event.target); + }, this), 300, this); }, this)); } } }, - // Destroy - unbind - the plugin. + /** + * Unbinds the whole plugin. + */ destroy: function() { this.$container.remove(); this.$select.show(); + + // reset original state + this.$select.prop('disabled', this.options.wasDisabled); + + this.$select.data('multiselect', null); }, - // Refreshs the checked options based on the current state of the select. - refresh: function() { - $('option', this.$select).each($.proxy(function(index, element) { - var $input = $('li input', this.$ul).filter(function() { - return $(this).val() == $(element).val(); - }); + /** + * Refreshs the multiselect based on the selected options of the select. + */ + refresh: function () { + var inputs = {}; + $('li input', this.$ul).each(function() { + inputs[$(this).val()] = $(this); + }); - if ($(element).is(':selected')) { + $('option', this.$select).each($.proxy(function (index, element) { + var $elem = $(element); + var $input = inputs[$(element).val()]; + + if ($elem.is(':selected')) { $input.prop('checked', true); if (this.options.selectedClass) { - $input.parents('li').addClass(this.options.selectedClass); + $input.closest('li') + .addClass(this.options.selectedClass); } } else { $input.prop('checked', false); if (this.options.selectedClass) { - $input.parents('li').removeClass(this.options.selectedClass); + $input.closest('li') + .removeClass(this.options.selectedClass); } } - if ($(element).is(":disabled")) { - $input.attr('disabled', 'disabled').prop('disabled', true).parents('li').addClass('disabled'); + if ($elem.is(":disabled")) { + $input.attr('disabled', 'disabled') + .prop('disabled', true) + .closest('li') + .addClass('disabled'); } else { - $input.removeAttr('disabled').prop('disabled', false).parents('li').removeClass('disabled'); + $input.prop('disabled', false) + .closest('li') + .removeClass('disabled'); } }, this)); this.updateButtonText(); + this.updateSelectAll(); + + if (this.options.enableClickableOptGroups && this.options.multiple) { + this.updateOptGroups(); + } }, - // Select an option by its value or multiple options using an array of values. - select: function(selectValues) { - if(selectValues && !$.isArray(selectValues)) { + /** + * Select all options of the given values. + * + * If triggerOnChange is set to true, the on change event is triggered if + * and only if one value is passed. + * + * @param {Array} selectValues + * @param {Boolean} triggerOnChange + */ + select: function(selectValues, triggerOnChange) { + if(!$.isArray(selectValues)) { selectValues = [selectValues]; } - + for (var i = 0; i < selectValues.length; i++) { - var value = selectValues[i]; - + + if (value === null || value === undefined) { + continue; + } + var $option = this.getOptionByValue(value); var $checkbox = this.getInputByValue(value); + if($option === undefined || $checkbox === undefined) { + continue; + } + + if (!this.options.multiple) { + this.deselectAll(false); + } + if (this.options.selectedClass) { - $checkbox.parents('li').addClass(this.options.selectedClass); + $checkbox.closest('li') + .addClass(this.options.selectedClass); } $checkbox.prop('checked', true); + $option.prop('selected', true); - $option.attr('selected', 'selected').prop('selected', true); - this.options.onChange($option, true); + if (triggerOnChange) { + this.options.onChange($option, true); + } } this.updateButtonText(); + this.updateSelectAll(); + + if (this.options.enableClickableOptGroups && this.options.multiple) { + this.updateOptGroups(); + } }, - // Deselect an option by its value or using an array of values. - deselect: function(deselectValues) { - if(deselectValues && !$.isArray(deselectValues)) { + /** + * Clears all selected items. + */ + clearSelection: function () { + this.deselectAll(false); + this.updateButtonText(); + this.updateSelectAll(); + + if (this.options.enableClickableOptGroups && this.options.multiple) { + this.updateOptGroups(); + } + }, + + /** + * Deselects all options of the given values. + * + * If triggerOnChange is set to true, the on change event is triggered, if + * and only if one value is passed. + * + * @param {Array} deselectValues + * @param {Boolean} triggerOnChange + */ + deselect: function(deselectValues, triggerOnChange) { + if(!$.isArray(deselectValues)) { deselectValues = [deselectValues]; } for (var i = 0; i < deselectValues.length; i++) { - var value = deselectValues[i]; - + + if (value === null || value === undefined) { + continue; + } + var $option = this.getOptionByValue(value); var $checkbox = this.getInputByValue(value); + if($option === undefined || $checkbox === undefined) { + continue; + } + if (this.options.selectedClass) { - $checkbox.parents('li').removeClass(this.options.selectedClass); + $checkbox.closest('li') + .removeClass(this.options.selectedClass); } $checkbox.prop('checked', false); + $option.prop('selected', false); - $option.removeAttr('selected').prop('selected', false); - this.options.onChange($option, false); + if (triggerOnChange) { + this.options.onChange($option, false); + } } this.updateButtonText(); + this.updateSelectAll(); + + if (this.options.enableClickableOptGroups && this.options.multiple) { + this.updateOptGroups(); + } }, - // Rebuild the whole dropdown menu. + /** + * Selects all enabled & visible options. + * + * If justVisible is true or not specified, only visible options are selected. + * + * @param {Boolean} justVisible + * @param {Boolean} triggerOnSelectAll + */ + selectAll: function (justVisible, triggerOnSelectAll) { + + var justVisible = typeof justVisible === 'undefined' ? true : justVisible; + var allLis = $("li:not(.divider):not(.disabled):not(.multiselect-group)", this.$ul); + var visibleLis = $("li:not(.divider):not(.disabled):not(.multiselect-group):not(.multiselect-filter-hidden):not(.multiselect-collapisble-hidden)", this.$ul).filter(':visible'); + + if(justVisible) { + $('input:enabled' , visibleLis).prop('checked', true); + visibleLis.addClass(this.options.selectedClass); + + $('input:enabled' , visibleLis).each($.proxy(function(index, element) { + var value = $(element).val(); + var option = this.getOptionByValue(value); + $(option).prop('selected', true); + }, this)); + } + else { + $('input:enabled' , allLis).prop('checked', true); + allLis.addClass(this.options.selectedClass); + + $('input:enabled' , allLis).each($.proxy(function(index, element) { + var value = $(element).val(); + var option = this.getOptionByValue(value); + $(option).prop('selected', true); + }, this)); + } + + $('li input[value="' + this.options.selectAllValue + '"]', this.$ul).prop('checked', true); + + if (this.options.enableClickableOptGroups && this.options.multiple) { + this.updateOptGroups(); + } + + if (triggerOnSelectAll) { + this.options.onSelectAll(); + } + }, + + /** + * Deselects all options. + * + * If justVisible is true or not specified, only visible options are deselected. + * + * @param {Boolean} justVisible + */ + deselectAll: function (justVisible, triggerOnDeselectAll) { + + var justVisible = typeof justVisible === 'undefined' ? true : justVisible; + var allLis = $("li:not(.divider):not(.disabled):not(.multiselect-group)", this.$ul); + var visibleLis = $("li:not(.divider):not(.disabled):not(.multiselect-group):not(.multiselect-filter-hidden):not(.multiselect-collapisble-hidden)", this.$ul).filter(':visible'); + + if(justVisible) { + $('input[type="checkbox"]:enabled' , visibleLis).prop('checked', false); + visibleLis.removeClass(this.options.selectedClass); + + $('input[type="checkbox"]:enabled' , visibleLis).each($.proxy(function(index, element) { + var value = $(element).val(); + var option = this.getOptionByValue(value); + $(option).prop('selected', false); + }, this)); + } + else { + $('input[type="checkbox"]:enabled' , allLis).prop('checked', false); + allLis.removeClass(this.options.selectedClass); + + $('input[type="checkbox"]:enabled' , allLis).each($.proxy(function(index, element) { + var value = $(element).val(); + var option = this.getOptionByValue(value); + $(option).prop('selected', false); + }, this)); + } + + $('li input[value="' + this.options.selectAllValue + '"]', this.$ul).prop('checked', false); + + if (this.options.enableClickableOptGroups && this.options.multiple) { + this.updateOptGroups(); + } + + if (triggerOnDeselectAll) { + this.options.onDeselectAll(); + } + }, + + /** + * Rebuild the plugin. + * + * Rebuilds the dropdown, the filter and the select all option. + */ rebuild: function() { this.$ul.html(''); - - // Remove select all option in select. - $('option[value="' + this.options.selectAllValue + '"]', this.$select).remove(); - + // Important to distinguish between radios and checkboxes. - this.options.multiple = this.$select.attr('multiple') == "multiple"; - + this.options.multiple = this.$select.attr('multiple') === "multiple"; + this.buildSelectAll(); this.buildDropdownOptions(); - this.updateButtonText(); this.buildFilter(); + + this.updateButtonText(); + this.updateSelectAll(true); + + if (this.options.enableClickableOptGroups && this.options.multiple) { + this.updateOptGroups(); + } + + if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) { + this.disable(); + } + else { + this.enable(); + } + + if (this.options.dropRight) { + this.$ul.addClass('pull-right'); + } }, - - // Build select using the given data as options. + + /** + * The provided data will be used to build the dropdown. + */ dataprovider: function(dataprovider) { - var optionDOM = ""; - dataprovider.forEach(function (option) { - optionDOM += ''; + + var groupCounter = 0; + var $select = this.$select.empty(); + + $.each(dataprovider, function (index, option) { + var $tag; + + if ($.isArray(option.children)) { // create optiongroup tag + groupCounter++; + + $tag = $('').attr({ + label: option.label || 'Group ' + groupCounter, + disabled: !!option.disabled, + value: option.value + }); + + forEach(option.children, function(subOption) { // add children option tags + var attributes = { + value: subOption.value, + label: subOption.label || subOption.value, + title: subOption.title, + selected: !!subOption.selected, + disabled: !!subOption.disabled + }; + + //Loop through attributes object and add key-value for each attribute + for (var key in subOption.attributes) { + attributes['data-' + key] = subOption.attributes[key]; + } + //Append original attributes + new data attributes to option + $tag.append($('