diff --git a/README.md b/README.md index 5095ccb..9a05cdb 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Bootstrap Multiselect Rails -Easily add [bootstrap-multiselect v0.9.9](https://github.com/davidstutz/bootstrap-multiselect.git) to your Rails application using the asset pipeline. +Easily add [bootstrap-multiselect v0.9.13](https://github.com/davidstutz/bootstrap-multiselect.git) to your Rails application using the asset pipeline. ## Installation diff --git a/bootstrap-multiselect-rails.gemspec b/bootstrap-multiselect-rails.gemspec index 53498d9..60e1195 100644 --- a/bootstrap-multiselect-rails.gemspec +++ b/bootstrap-multiselect-rails.gemspec @@ -8,8 +8,8 @@ Gem::Specification.new do |spec| spec.version = BootstrapMultiselect::Rails::VERSION spec.authors = ["Benjamin Canac"] spec.email = ["canacb1@gmail.com"] - spec.description = %q{Add Bootstrap Multiselect v0.9.9 to your rails app. See https://github.com/davidstutz/bootstrap-multiselect for more information about bootstrap-multiselect.} - spec.summary = %q{Add Bootstrap Multiselect v0.9.9 to your rails app.} + spec.description = %q{Add Bootstrap Multiselect v0.9.13 to your rails app. See https://github.com/davidstutz/bootstrap-multiselect for more information about bootstrap-multiselect.} + spec.summary = %q{Add Bootstrap Multiselect v0.9.13 to your rails app.} spec.homepage = "https://github.com/benjamincanac/bootstrap-multiselect-rails" spec.license = "MIT" diff --git a/lib/bootstrap-multiselect-rails/version.rb b/lib/bootstrap-multiselect-rails/version.rb index bbb8fbd..3ecfdb0 100644 --- a/lib/bootstrap-multiselect-rails/version.rb +++ b/lib/bootstrap-multiselect-rails/version.rb @@ -1,5 +1,5 @@ module BootstrapMultiselect module Rails - VERSION = '0.9.9' + VERSION = '0.9.13' end end \ No newline at end of file diff --git a/vendor/assets/javascripts/bootstrap-multiselect.js b/vendor/assets/javascripts/bootstrap-multiselect.js index 3e21e40..a7c71ea 100755 --- a/vendor/assets/javascripts/bootstrap-multiselect.js +++ b/vendor/assets/javascripts/bootstrap-multiselect.js @@ -1,104 +1,194 @@ /** - * Bootstrap Multiselect v0.9.8 (https://github.com/davidstutz/bootstrap-multiselect) + * Bootstrap Multiselect (https://github.com/davidstutz/bootstrap-multiselect) * - * Copyright 2012 - 2014 David Stutz + * Apache License, Version 2.0: + * Copyright (c) 2012 - 2015 David Stutz * - * Dual licensed under the BSD-3-Clause and the Apache License, Version 2.0. + * 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 - 2015 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 ($) { "use strict";// jshint ;_; if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) { ko.bindingHandlers.multiselect = { - - init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { - - var listOfSelectedItems = allBindingsAccessor().selectedOptions; - var config = ko.utils.unwrapObservable(valueAccessor()); - - $(element).multiselect(config); - - if (isObservableArray(listOfSelectedItems)) { - - // Set the initial selection state on the multiselect list. - $(element).multiselect('select', ko.utils.unwrapObservable(listOfSelectedItems)); - - // Subscribe to the selectedOptions: ko.observableArray - listOfSelectedItems.subscribe(function (changes) { - var addedArray = [], deletedArray = []; - forEach(changes, function (change) { - switch (change.status) { - case 'added': - addedArray.push(change.value); - break; - case 'deleted': - deletedArray.push(change.value); - break; - } + 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 }); - - if (addedArray.length > 0) { - $(element).multiselect('select', addedArray); - } - - if (deletedArray.length > 0) { - $(element).multiselect('deselect', deletedArray); - } - }, null, "arrayChange"); + } } - }, - update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + //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 }); + } + } - var listOfItems = allBindingsAccessor().options, - ms = $(element).data('multiselect'), - config = ko.utils.unwrapObservable(valueAccessor()); + //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 }); + } + } - if (isObservableArray(listOfItems)) { - // Subscribe to the options: ko.observableArray incase it changes later - listOfItems.subscribe(function (theArray) { - $(element).multiselect('rebuild'); + 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 (!ms) { - $(element).multiselect(config); - } - else { - ms.updateOriginalOptions(); + 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 isObservableArray(obj) { - return ko.isObservable(obj) && !(obj.destroyAll === undefined); - } - function forEach(array, callback) { for (var index = 0; index < array.length; ++index) { - callback(array[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); + + // Placeholder via data attributes + if (this.$select.attr("data-placeholder")) { + options.nonSelectedText = this.$select.data("placeholder"); + } + + this.options = this.mergeOptions($.extend({}, options, this.$select.data())); // 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.onChange = $.proxy(this.options.onChange, this); @@ -106,6 +196,7 @@ 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); // Build select all if enabled. this.buildContainer(); @@ -114,16 +205,17 @@ this.buildSelectAll(); this.buildDropdownOptions(); this.buildFilter(); - + this.updateButtonText(); - this.updateSelectAll(); - - if (this.options.disableIfEmpty) { - this.disableIfEmpty(); + this.updateSelectAll(true); + + if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) { + this.disable(); } this.$select.hide().after(this.$container); - }; + this.options.onInitialized(this.$select, this.$container); + } Multiselect.prototype = { @@ -138,23 +230,41 @@ * @returns {String} */ buttonText: function(options, select) { - if (options.length === 0) { - return this.nonSelectedText + ' '; + if (this.disabledText.length > 0 + && (this.disableIfEmpty || select.prop('disabled')) + && options.length == 0) { + + return this.disabledText; } - else { - if (options.length > this.numberDisplayed) { - 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 (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 - 2); + } }, /** * Updates the title of the button similar to the buttonText function. @@ -169,20 +279,32 @@ } else { var selected = ''; + var delimiter = this.delimiterText; + options.each(function () { - selected += $(this).text() + ', '; + var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text(); + selected += label + delimiter; }); return selected.substr(0, selected.length - 2); } }, /** * 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} */ - label: function(element){ - return $(element).attr('label') || $(element).html(); + optionClass: function(element) { + return $(element).attr('class') || ''; }, /** * Triggered on change of the multiselect. @@ -197,19 +319,19 @@ }, /** * 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. @@ -227,11 +349,29 @@ onDropdownHidden: function(event) { }, + /** + * Triggered on select all. + */ + onSelectAll: function(checked) { + + }, + /** + * Triggered after initializing. + * + * @param {jQuery} $select + * @param {jQuery} $container + */ + onInitialized: function($select, $container) { + + }, + enableHTML: false, buttonClass: 'btn btn-default', - dropRight: false, - selectedClass: 'active', + 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, @@ -240,23 +380,34 @@ includeSelectAllIfMoreThan: 0, selectAllText: ' Select all', selectAllValue: 'multiselect-all', + selectAllName: false, + selectAllNumber: true, + selectAllJustVisible: true, enableFiltering: false, enableCaseInsensitiveFiltering: false, + enableFullValueFiltering: false, + enableClickableOptGroups: false, + enableCollapsibelOptGroups: false, filterPlaceholder: 'Search', // possible options: 'text', 'value', 'both' filterBehavior: 'text', + includeFilterClearBtn: true, preventInputChangeEvent: false, nonSelectedText: 'None selected', nSelectedText: 'selected', + allSelectedText: 'All selected', numberDisplayed: 3, disableIfEmpty: false, + disabledText: '', + delimiterText: ', ', templates: { - button: '', + button: '', ul: '', filter: '
  • ', - li: '
  • ', + filterClearBtn: '', + li: '
  • ', divider: '
  • ', - liGroup: '
  • ' + liGroup: '
  • ' } }, @@ -278,7 +429,9 @@ */ buildButton: function() { 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.prop('disabled')) { this.disable(); @@ -290,7 +443,9 @@ // Manually add button width if set. if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') { this.$button.css({ - 'width' : this.options.buttonWidth + 'width' : this.options.buttonWidth, + 'overflow' : 'hidden', + 'text-overflow' : 'ellipsis' }); this.$container.css({ 'width': this.options.buttonWidth @@ -327,7 +482,20 @@ 'overflow-x': 'hidden' }); } - + + 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); }, @@ -339,12 +507,13 @@ 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') + var tag = $element.prop('tagName') .toLowerCase(); - if ($(element).prop('value') === this.options.selectAllValue) { + if ($element.prop('value') === this.options.selectAllValue) { return; } @@ -353,7 +522,7 @@ } else if (tag === 'option') { - if ($(element).data('role') === 'divider') { + if ($element.data('role') === 'divider') { this.createDivider(); } else { @@ -361,7 +530,7 @@ } } - + // Other illegal tags will be ignored. }, this)); @@ -375,11 +544,11 @@ // Apply or unapply the configured selected class. if (this.options.selectedClass) { if (checked) { - $target.parents('li') + $target.closest('li') .addClass(this.options.selectedClass); } else { - $target.parents('li') + $target.closest('li') .removeClass(this.options.selectedClass); } } @@ -393,14 +562,13 @@ if (isSelectAllOption) { if (checked) { - this.selectAll(); + this.selectAll(this.options.selectAllJustVisible); } else { - this.deselectAll(); + this.deselectAll(this.options.selectAllJustVisible); } } - - if(!isSelectAllOption){ + else { if (checked) { $option.prop('selected', true); @@ -411,7 +579,7 @@ else { // Unselect all other options and corresponding checkboxes. if (this.options.selectedClass) { - $($checkboxesNotThis).parents('li').removeClass(this.options.selectedClass); + $($checkboxesNotThis).closest('li').removeClass(this.options.selectedClass); } $($checkboxesNotThis).prop('checked', false); @@ -422,74 +590,99 @@ } if (this.options.selectedClass === "active") { - $optionsNotThis.parents("a").css("outline", ""); + $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); } this.$select.change(); this.updateButtonText(); this.updateSelectAll(); - - this.options.onChange($option, checked); if(this.options.preventInputChangeEvent) { return false; } }, this)); - $('li a', this.$ul).on('touchstart click', function(event) { + $('li a', this.$ul).on('mousedown', function(e) { + if (e.shiftKey) { + // Prevent selecting text by Shift+click + return false; + } + }); + + $('li a', this.$ul).on('touchstart click', $.proxy(function(event) { event.stopPropagation(); var $target = $(event.target); - - if (event.shiftKey) { + + 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 (checked) { - var prev = $target.parents('li:last') - .siblings('li[class="active"]:first'); - - var currentIdx = $target.parents('li') - .index(); - var prevIdx = prev.index(); - - if (currentIdx > prevIdx) { - $target.parents("li:last").prevUntil(prev).each( - function() { - $(this).find("input:first").prop("checked", true) - .trigger("change"); - } - ); + if (this.lastToggledInput !== null && this.lastToggledInput !== $target) { // Make sure we actually have a range + var from = $target.closest("li").index(); + var to = this.lastToggledInput.closest("li").index(); + + if (from > to) { // Swap the indices + var tmp = to; + to = from; + from = tmp; } - else { - $target.parents("li:last").nextUntil(prev).each( - function() { - $(this).find("input:first").prop("checked", true) - .trigger("change"); - } - ); + + // 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").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.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 { @@ -527,35 +720,153 @@ event.preventDefault(); } }, this)); + + if(this.options.enableClickableOptGroups && this.options.multiple) { + $('li.multiselect-group', this.$ul).on('click', $.proxy(function(event) { + event.stopPropagation(); + console.log('test'); + var group = $(event.target).parent(); + + // Search all option in optgroup + var $options = group.nextUntil('li.multiselect-group'); + var $visibleOptions = $options.filter(":visible:not(.disabled)"); + + // check or uncheck items + var allChecked = true; + var optionInputs = $visibleOptions.find('input'); + var values = []; + + optionInputs.each(function() { + allChecked = allChecked && $(this).prop('checked'); + values.push($(this).val()); + }); + + if (!allChecked) { + this.select(values, false); + } + else { + this.deselect(values, false); + } + + this.options.onChange(optionInputs, !allChecked); + }, this)); + } + + if (this.options.enableCollapsibleOptGroups && this.options.multiple) { + $("li.multiselect-group input", this.$ul).off(); + $("li.multiselect-group", this.$ul).siblings().not("li.multiselect-group, li.multiselect-all", this.$ul).each( function () { + $(this).toggleClass('hidden', true); + }); + + $("li.multiselect-group", this.$ul).on("click", $.proxy(function(group) { + group.stopPropagation(); + }, this)); + + $("li.multiselect-group > a > b", this.$ul).on("click", $.proxy(function(t) { + t.stopPropagation(); + var n = $(t.target).closest('li'); + var r = n.nextUntil("li.multiselect-group"); + var i = true; + + r.each(function() { + i = i && $(this).hasClass('hidden'); + }); + + r.toggleClass('hidden', !i); + }, this)); + + $("li.multiselect-group > a > input", this.$ul).on("change", $.proxy(function(t) { + t.stopPropagation(); + var n = $(t.target).closest('li'); + var r = n.nextUntil("li.multiselect-group", ':not(.disabled)'); + var s = r.find("input"); + + var i = true; + s.each(function() { + i = i && $(this).prop("checked"); + }); + + s.prop("checked", !i).trigger("change"); + }, this)); + + // Set the initial selection state of the groups. + $('li.multiselect-group', this.$ul).each(function() { + var r = $(this).nextUntil("li.multiselect-group", ':not(.disabled)'); + var s = r.find("input"); + + var i = true; + s.each(function() { + i = i && $(this).prop("checked"); + }); + + $(this).find('input').prop("checked", i); + }); + + // Update the group checkbox based on new selections among the + // corresponding children. + $("li input", this.$ul).on("change", $.proxy(function(t) { + t.stopPropagation(); + var n = $(t.target).closest('li'); + var r1 = n.prevUntil("li.multiselect-group", ':not(.disabled)'); + var r2 = n.nextUntil("li.multiselect-group", ':not(.disabled)'); + var s1 = r1.find("input"); + var s2 = r2.find("input"); + + var i = $(t.target).prop('checked'); + s1.each(function() { + i = i && $(this).prop("checked"); + }); + + s2.each(function() { + i = i && $(this).prop("checked"); + }); + + n.prevAll('.multiselect-group').find('input').prop('checked', i); + }, this)); + + $("li.multiselect-all", this.$ul).css('background', '#f3f3f3').css('border-bottom', '1px solid #eaeaea'); + $("li.multiselect-group > a, 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'); + } }, /** * Create an option using the given select option. - * + * * @param {jQuery} element */ createOptionValue: function(element) { - if ($(element).is(':selected')) { - $(element).prop('selected', true); + var $element = $(element); + if ($element.is(':selected')) { + $element.prop('selected', true); } // Support the label attribute on options. - var label = this.options.label(element); - 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.options.templates.li); - $('label', $li).addClass(inputType); - - if (this.options.checkboxName) { - $('label', $li).append(''); + var $label = $('label', $li); + $label.addClass(inputType); + $li.addClass(classes); + + if (this.options.enableHTML) { + $label.html(" " + label); } else { - $('label', $li).append(''); + $label.text(" " + label); } - - var selected = $(element).prop('selected') || false; - var $checkbox = $('input', $li); + + var $checkbox = $('').attr('type', inputType); + + if (this.options.checkboxName) { + $checkbox.attr('name', this.options.checkboxName); + } + $label.prepend($checkbox); + + var selected = $element.prop('selected') || false; $checkbox.val(value); if (value === this.options.selectAllValue) { @@ -564,30 +875,30 @@ .addClass('multiselect-all'); } - $('label', $li).append(" " + label); + $label.attr('title', $element.attr('title')); this.$ul.append($li); - if ($(element).is(':disabled')) { + if ($element.is(':disabled')) { $checkbox.attr('disabled', 'disabled') .prop('disabled', true) - .parents('a') + .closest('a') .attr("tabindex", "-1") - .parents('li') + .closest('li') .addClass('disabled'); } $checkbox.prop('checked', selected); if (selected && this.options.selectedClass) { - $checkbox.parents('li') + $checkbox.closest('li') .addClass(this.options.selectedClass); } }, /** * Creates a divider using the given select option. - * + * * @param {jQuery} element */ createDivider: function(element) { @@ -597,39 +908,71 @@ /** * Creates an optgroup. - * + * * @param {jQuery} group */ - createOptgroup: function(group) { - var groupName = $(group).prop('label'); + createOptgroup: function(group) { + if (this.options.enableCollapsibleOptGroups && this.options.multiple) { + var label = $(group).attr("label"); + var value = $(group).attr("value"); + var r = $('
  • ' + label + '
  • '); + + if (this.options.enableClickableOptGroups) { + r.addClass("multiselect-group-clickable") + } + this.$ul.append(r); + if ($(group).is(":disabled")) { + r.addClass("disabled") + } + $("option", group).each($.proxy(function($, group) { + this.createOptionValue(group) + }, this)) + } + else { + var groupName = $(group).prop('label'); - // Add a header for the group. - var $li = $(this.options.templates.liGroup); - $('label', $li).text(groupName); + // Add a header for the group. + var $li = $(this.options.templates.liGroup); - this.$ul.append($li); + if (this.options.enableHTML) { + $('label', $li).html(groupName); + } + else { + $('label', $li).text(groupName); + } - if ($(group).is(':disabled')) { - $li.addClass('disabled'); - } + if (this.options.enableClickableOptGroups) { + $li.addClass('multiselect-group-clickable'); + } - // Add the options of the group. - $('option', group).each($.proxy(function(index, element) { - this.createOptionValue(element); - }, this)); + this.$ul.append($li); + + if ($(group).is(':disabled')) { + $li.addClass('disabled'); + } + + // Add the options of the group. + $('option', group).each($.proxy(function(index, element) { + this.createOptionValue(element); + }, this)); + } }, /** - * Build the selct all. + * Build the select all. * * Checks if a select all has already been created. */ buildSelectAll: function() { - var alreadyHasSelectAll = this.hasSelectAll(); + 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)); @@ -638,11 +981,18 @@ var $li = $(this.options.templates.li); $('label', $li).addClass("checkbox"); - if (this.options.checkboxName) { - $('label', $li).append(''); + 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).append(''); + $('label', $li).prepend(''); } var $checkbox = $('input', $li); @@ -652,8 +1002,6 @@ $checkbox.parent().parent() .addClass('multiselect-all'); - $('label', $li).append(" " + this.options.selectAllText); - this.$ul.prepend($li); $checkbox.prop('checked', false); @@ -673,11 +1021,29 @@ 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.$filter.find('.multiselect-search').val(''); + $('li', this.$ul).show().removeClass("filter-hidden"); + this.updateSelectAll(); + }, 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('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); @@ -686,8 +1052,9 @@ 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(); + var value = $('input', element).length > 0 ? $('input', element).val() : ""; var text = $('label', element).text(); var filterCandidate = ''; @@ -702,22 +1069,45 @@ } 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.toLowerCase().indexOf(this.query.toLowerCase()) > -1) { - showElement = true; + 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; } - if (showElement) { - $(element).show().removeClass("filter-hidden"); + // Toggle current element (group or group item) according to showElement boolean. + $(element).toggle(showElement).toggleClass('filter-hidden', !showElement); + + // Differentiate groups and group items. + if ($(element).hasClass('multiselect-group')) { + // Remember group status. + currentGroup = element; + currentGroupVisible = showElement; } else { - $(element).hide().addClass("filter-hidden"); + // Show group name when at least one of its items is visible. + if (showElement) { + $(currentGroup).show().removeClass('filter-hidden'); + } + + // Show all group items when group name satisfies filter. + if (!showElement && currentGroupVisible) { + $(element).show().removeClass('filter-hidden'); + } } } }, this)); @@ -742,39 +1132,46 @@ /** * Refreshs the multiselect based on the selected options 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(); - }); - - if ($(element).is(':selected')) { - $input.prop('checked', true); - - if (this.options.selectedClass) { - $input.parents('li') - .addClass(this.options.selectedClass); + refresh: function () { + var inputs = $.map($('li input', this.$ul), $); + + $('option', this.$select).each($.proxy(function (index, element) { + var $elem = $(element); + var value = $elem.val(); + var $input; + for (var i = inputs.length; 0 < i--; /**/) { + if (value !== ($input = inputs[i]).val()) + continue; // wrong li + + if ($elem.is(':selected')) { + $input.prop('checked', true); + + if (this.options.selectedClass) { + $input.closest('li') + .addClass(this.options.selectedClass); + } } - } - else { - $input.prop('checked', false); + else { + $input.prop('checked', false); - if (this.options.selectedClass) { - $input.parents('li') - .removeClass(this.options.selectedClass); + if (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'); - } - else { - $input.prop('disabled', false) - .parents('li') - .removeClass('disabled'); + if ($elem.is(":disabled")) { + $input.attr('disabled', 'disabled') + .prop('disabled', true) + .closest('li') + .addClass('disabled'); + } + else { + $input.prop('disabled', false) + .closest('li') + .removeClass('disabled'); + } + break; // assumes unique values } }, this)); @@ -799,6 +1196,10 @@ 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); @@ -811,19 +1212,20 @@ } if (this.options.selectedClass) { - $checkbox.parents('li') + $checkbox.closest('li') .addClass(this.options.selectedClass); } $checkbox.prop('checked', true); $option.prop('selected', true); + + if (triggerOnChange) { + this.options.onChange($option, true); + } } this.updateButtonText(); - - if (triggerOnChange && selectValues.length === 1) { - this.options.onChange($option, true); - } + this.updateSelectAll(); }, /** @@ -850,9 +1252,12 @@ } 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); @@ -861,35 +1266,50 @@ } if (this.options.selectedClass) { - $checkbox.parents('li') + $checkbox.closest('li') .removeClass(this.options.selectedClass); } $checkbox.prop('checked', false); $option.prop('selected', false); + + if (triggerOnChange) { + this.options.onChange($option, false); + } } this.updateButtonText(); - - if (triggerOnChange && deselectValues.length === 1) { - this.options.onChange($option, false); - } + this.updateSelectAll(); }, /** * 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 () { + selectAll: function (justVisible, triggerOnSelectAll) { + justVisible = (this.options.enableCollapsibleOptGroups && this.options.multiple) ? false : justVisible; + + var justVisible = typeof justVisible === 'undefined' ? true : justVisible; var allCheckboxes = $("li input[type='checkbox']:enabled", this.$ul); var visibleCheckboxes = allCheckboxes.filter(":visible"); var allCheckboxesCount = allCheckboxes.length; var visibleCheckboxesCount = visibleCheckboxes.length; - - visibleCheckboxes.prop('checked', true); - $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").addClass(this.options.selectedClass); - if (allCheckboxesCount === visibleCheckboxesCount) { - $("option:enabled", this.$select).prop('selected', true); + if(justVisible) { + visibleCheckboxes.prop('checked', true); + $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").addClass(this.options.selectedClass); + } + else { + allCheckboxes.prop('checked', true); + $("li:not(.divider):not(.disabled)", this.$ul).addClass(this.options.selectedClass); + } + + if (allCheckboxesCount === visibleCheckboxesCount || justVisible === false) { + $("option:not([data-role='divider']):enabled", this.$select).prop('selected', true); } else { var values = visibleCheckboxes.map(function() { @@ -900,6 +1320,10 @@ return $.inArray($(this).val(), values) !== -1; }).prop('selected', true); } + + if (triggerOnSelectAll) { + this.options.onSelectAll(); + } }, /** @@ -910,10 +1334,11 @@ * @param {Boolean} justVisible */ deselectAll: function (justVisible) { - var justVisible = typeof justVisible === 'undefined' ? true : justVisible; + justVisible = (this.options.enableCollapsibleOptGroups && this.options.multiple) ? false : justVisible; + justVisible = typeof justVisible === 'undefined' ? true : justVisible; if(justVisible) { - var visibleCheckboxes = $("li input[type='checkbox']:enabled", this.$ul).filter(":visible"); + var visibleCheckboxes = $("li input[type='checkbox']:not(:disabled)", this.$ul).filter(":visible"); visibleCheckboxes.prop('checked', false); var values = visibleCheckboxes.map(function() { @@ -952,12 +1377,15 @@ this.buildSelectAll(); this.buildDropdownOptions(); this.buildFilter(); - + this.updateButtonText(); - this.updateSelectAll(); + this.updateSelectAll(true); - if (this.options.disableIfEmpty) { - this.disableIfEmpty(); + if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) { + this.disable(); + } + else { + this.enable(); } if (this.options.dropRight) { @@ -967,30 +1395,48 @@ /** * The provided data will be used to build the dropdown. - * - * @param {Array} dataprovider */ dataprovider: function(dataprovider) { - var optionDOM = ""; + var groupCounter = 0; - + var $select = this.$select.empty(); + $.each(dataprovider, function (index, option) { - if ($.isArray(option.children)) { + var $tag; + + if ($.isArray(option.children)) { // create optiongroup tag groupCounter++; - optionDOM += ''; - - forEach(option.children, function(subOption) { - optionDOM += ''; + + $tag = $('').attr({ + label: option.label || 'Group ' + groupCounter, + disabled: !!option.disabled + }); + + forEach(option.children, function(subOption) { // add children option tags + $tag.append($(''; } else { - optionDOM += ''; + $tag = $('