(function ($) {
'use strict';
var DISALLOWED_ATTRIBUTES = ['sanitize', 'whiteList', 'sanitizeFn'];
var uriAttrs = [
'background',
'cite',
'href',
'itemtype',
'longdesc',
'poster',
'src',
'xlink:href'
];
var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i;
var DefaultWhitelist = {
// Global attributes allowed on any supplied element below.
'*': ['class', 'dir', 'id', 'lang', 'role', 'tabindex', 'style', ARIA_ATTRIBUTE_PATTERN],
a: ['target', 'href', 'title', 'rel'],
area: [],
b: [],
br: [],
col: [],
code: [],
div: [],
em: [],
hr: [],
h1: [],
h2: [],
h3: [],
h4: [],
h5: [],
h6: [],
i: [],
img: ['src', 'alt', 'title', 'width', 'height'],
li: [],
ol: [],
p: [],
pre: [],
s: [],
small: [],
span: [],
sub: [],
sup: [],
strong: [],
u: [],
ul: []
}
/**
* A pattern that recognizes a commonly useful subset of URLs that are safe.
*
* Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
*/
var SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi;
/**
* A pattern that matches safe data URLs. Only matches image, video and audio types.
*
* Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
*/
var DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+/]+=*$/i;
function allowedAttribute (attr, allowedAttributeList) {
var attrName = attr.nodeName.toLowerCase()
if ($.inArray(attrName, allowedAttributeList) !== -1) {
if ($.inArray(attrName, uriAttrs) !== -1) {
return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN))
}
return true
}
var regExp = $(allowedAttributeList).filter(function (index, value) {
return value instanceof RegExp
})
// Check if a regular expression validates the attribute.
for (var i = 0, l = regExp.length; i < l; i++) {
if (attrName.match(regExp[i])) {
return true
}
}
return false
}
function sanitizeHtml (unsafeElements, whiteList, sanitizeFn) {
if (sanitizeFn && typeof sanitizeFn === 'function') {
return sanitizeFn(unsafeElements);
}
var whitelistKeys = Object.keys(whiteList);
for (var i = 0, len = unsafeElements.length; i < len; i++) {
var elements = unsafeElements[i].querySelectorAll('*');
for (var j = 0, len2 = elements.length; j < len2; j++) {
var el = elements[j];
var elName = el.nodeName.toLowerCase();
if (whitelistKeys.indexOf(elName) === -1) {
el.parentNode.removeChild(el);
continue;
}
var attributeList = [].slice.call(el.attributes);
var whitelistedAttributes = [].concat(whiteList['*'] || [], whiteList[elName] || []);
for (var k = 0, len3 = attributeList.length; k < len3; k++) {
var attr = attributeList[k];
if (!allowedAttribute(attr, whitelistedAttributes)) {
el.removeAttribute(attr.nodeName);
}
}
}
}
}
// Polyfill for browsers with no classList support
// Remove in v2
if (!('classList' in document.createElement('_'))) {
(function (view) {
if (!('Element' in view)) return;
var classListProp = 'classList',
protoProp = 'prototype',
elemCtrProto = view.Element[protoProp],
objCtr = Object,
classListGetter = function () {
var $elem = $(this);
return {
add: function (classes) {
classes = Array.prototype.slice.call(arguments).join(' ');
return $elem.addClass(classes);
},
remove: function (classes) {
classes = Array.prototype.slice.call(arguments).join(' ');
return $elem.removeClass(classes);
},
toggle: function (classes, force) {
return $elem.toggleClass(classes, force);
},
contains: function (classes) {
return $elem.hasClass(classes);
}
}
};
if (objCtr.defineProperty) {
var classListPropDesc = {
get: classListGetter,
enumerable: true,
configurable: true
};
try {
objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
} catch (ex) { // IE 8 doesn't support enumerable:true
// adding undefined to fight this issue https://github.com/eligrey/classList.js/issues/36
// modernie IE8-MSW7 machine has IE8 8.0.6001.18702 and is affected
if (ex.number === undefined || ex.number === -0x7FF5EC54) {
classListPropDesc.enumerable = false;
objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
}
}
} else if (objCtr[protoProp].__defineGetter__) {
elemCtrProto.__defineGetter__(classListProp, classListGetter);
}
}(window));
}
var testElement = document.createElement('_');
testElement.classList.add('c1', 'c2');
if (!testElement.classList.contains('c2')) {
var _add = DOMTokenList.prototype.add,
_remove = DOMTokenList.prototype.remove;
DOMTokenList.prototype.add = function () {
Array.prototype.forEach.call(arguments, _add.bind(this));
}
DOMTokenList.prototype.remove = function () {
Array.prototype.forEach.call(arguments, _remove.bind(this));
}
}
testElement.classList.toggle('c3', false);
// Polyfill for IE 10 and Firefox <24, where classList.toggle does not
// support the second argument.
if (testElement.classList.contains('c3')) {
var _toggle = DOMTokenList.prototype.toggle;
DOMTokenList.prototype.toggle = function (token, force) {
if (1 in arguments && !this.contains(token) === !force) {
return force;
} else {
return _toggle.call(this, token);
}
};
}
testElement = null;
// shallow array comparison
function isEqual (array1, array2) {
return array1.length === array2.length && array1.every(function (element, index) {
return element === array2[index];
});
};
//
if (!String.prototype.startsWith) {
(function () {
'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
var defineProperty = (function () {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
var object = {};
var $defineProperty = Object.defineProperty;
var result = $defineProperty(object, object, object) && $defineProperty;
} catch (error) {
}
return result;
}());
var toString = {}.toString;
var startsWith = function (search) {
if (this == null) {
throw new TypeError();
}
var string = String(this);
if (search && toString.call(search) == '[object RegExp]') {
throw new TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
// `ToInteger`
var pos = position ? Number(position) : 0;
if (pos != pos) { // better `isNaN`
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
// Avoid the `indexOf` call if no match is possible
if (searchLength + start > stringLength) {
return false;
}
var index = -1;
while (++index < searchLength) {
if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {
return false;
}
}
return true;
};
if (defineProperty) {
defineProperty(String.prototype, 'startsWith', {
'value': startsWith,
'configurable': true,
'writable': true
});
} else {
String.prototype.startsWith = startsWith;
}
}());
}
if (!Object.keys) {
Object.keys = function (
o, // object
k, // key
r // result array
) {
// initialize object and result
r = [];
// iterate over object keys
for (k in o) {
// fill result array with non-prototypical keys
r.hasOwnProperty.call(o, k) && r.push(k);
}
// return result
return r;
};
}
if (!HTMLSelectElement.prototype.hasOwnProperty('selectedOptions')) {
Object.defineProperty(HTMLSelectElement.prototype, 'selectedOptions', {
get: function () {
return this.querySelectorAll(':checked');
}
});
}
// much faster than $.val()
function getSelectValues (select) {
var result = [];
var options = select.selectedOptions;
var opt;
if (select.multiple) {
for (var i = 0, len = options.length; i < len; i++) {
opt = options[i];
result.push(opt.value || opt.text);
}
} else {
result = select.value;
}
return result;
}
// set data-selected on select element if the value has been programmatically selected
// prior to initialization of bootstrap-select
// * consider removing or replacing an alternative method *
var valHooks = {
useDefault: false,
_set: $.valHooks.select.set
};
$.valHooks.select.set = function (elem, value) {
if (value && !valHooks.useDefault) $(elem).data('selected', true);
return valHooks._set.apply(this, arguments);
};
var changedArguments = null;
var EventIsSupported = (function () {
try {
new Event('change');
return true;
} catch (e) {
return false;
}
})();
$.fn.triggerNative = function (eventName) {
var el = this[0],
event;
if (el.dispatchEvent) { // for modern browsers & IE9+
if (EventIsSupported) {
// For modern browsers
event = new Event(eventName, {
bubbles: true
});
} else {
// For IE since it doesn't support Event constructor
event = document.createEvent('Event');
event.initEvent(eventName, true, false);
}
el.dispatchEvent(event);
} else if (el.fireEvent) { // for IE8
event = document.createEventObject();
event.eventType = eventName;
el.fireEvent('on' + eventName, event);
} else {
// fall back to jQuery.trigger
this.trigger(eventName);
}
};
//
function stringSearch (li, searchString, method, normalize) {
var stringTypes = [
'content',
'subtext',
'tokens'
],
searchSuccess = false;
for (var i = 0; i < stringTypes.length; i++) {
var stringType = stringTypes[i],
string = li[stringType];
if (string) {
string = string.toString();
// Strip HTML tags. This isn't perfect, but it's much faster than any other method
if (stringType === 'content') {
string = string.replace(/<[^>]+>/g, '');
}
if (normalize) string = normalizeToBase(string);
string = string.toUpperCase();
if (method === 'contains') {
searchSuccess = string.indexOf(searchString) >= 0;
} else {
searchSuccess = string.startsWith(searchString);
}
if (searchSuccess) break;
}
}
return searchSuccess;
}
function toInteger (value) {
return parseInt(value, 10) || 0;
}
// Borrowed from Lodash (_.deburr)
/** Used to map Latin Unicode letters to basic Latin letters. */
var deburredLetters = {
// Latin-1 Supplement block.
'\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
'\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
'\xc7': 'C', '\xe7': 'c',
'\xd0': 'D', '\xf0': 'd',
'\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
'\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
'\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
'\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
'\xd1': 'N', '\xf1': 'n',
'\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
'\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
'\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
'\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
'\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
'\xc6': 'Ae', '\xe6': 'ae',
'\xde': 'Th', '\xfe': 'th',
'\xdf': 'ss',
// Latin Extended-A block.
'\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
'\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
'\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
'\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
'\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
'\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
'\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
'\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
'\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
'\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
'\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
'\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
'\u0134': 'J', '\u0135': 'j',
'\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
'\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
'\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
'\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
'\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
'\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
'\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
'\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
'\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
'\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
'\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
'\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
'\u0163': 't', '\u0165': 't', '\u0167': 't',
'\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
'\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
'\u0174': 'W', '\u0175': 'w',
'\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
'\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
'\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
'\u0132': 'IJ', '\u0133': 'ij',
'\u0152': 'Oe', '\u0153': 'oe',
'\u0149': "'n", '\u017f': 's'
};
/** Used to match Latin Unicode letters (excluding mathematical operators). */
var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
/** Used to compose unicode character classes. */
var rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboMarksExtendedRange = '\\u1ab0-\\u1aff',
rsComboMarksSupplementRange = '\\u1dc0-\\u1dff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange + rsComboMarksExtendedRange + rsComboMarksSupplementRange;
/** Used to compose unicode capture groups. */
var rsCombo = '[' + rsComboRange + ']';
/**
* Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
* [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
*/
var reComboMark = RegExp(rsCombo, 'g');
function deburrLetter (key) {
return deburredLetters[key];
};
function normalizeToBase (string) {
string = string.toString();
return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
}
// List of HTML entities for escaping.
var escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`'
};
// Functions for escaping and unescaping strings to/from HTML interpolation.
var createEscaper = function (map) {
var escaper = function (match) {
return map[match];
};
// Regexes for identifying a key that needs to be escaped.
var source = '(?:' + Object.keys(map).join('|') + ')';
var testRegexp = RegExp(source);
var replaceRegexp = RegExp(source, 'g');
return function (string) {
string = string == null ? '' : '' + string;
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
};
};
var htmlEscape = createEscaper(escapeMap);
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var keyCodeMap = {
32: ' ',
48: '0',
49: '1',
50: '2',
51: '3',
52: '4',
53: '5',
54: '6',
55: '7',
56: '8',
57: '9',
59: ';',
65: 'A',
66: 'B',
67: 'C',
68: 'D',
69: 'E',
70: 'F',
71: 'G',
72: 'H',
73: 'I',
74: 'J',
75: 'K',
76: 'L',
77: 'M',
78: 'N',
79: 'O',
80: 'P',
81: 'Q',
82: 'R',
83: 'S',
84: 'T',
85: 'U',
86: 'V',
87: 'W',
88: 'X',
89: 'Y',
90: 'Z',
96: '0',
97: '1',
98: '2',
99: '3',
100: '4',
101: '5',
102: '6',
103: '7',
104: '8',
105: '9'
};
var keyCodes = {
ESCAPE: 27, // KeyboardEvent.which value for Escape (Esc) key
ENTER: 13, // KeyboardEvent.which value for Enter key
SPACE: 32, // KeyboardEvent.which value for space key
TAB: 9, // KeyboardEvent.which value for tab key
ARROW_UP: 38, // KeyboardEvent.which value for up arrow key
ARROW_DOWN: 40 // KeyboardEvent.which value for down arrow key
}
var version = {
success: false,
major: '3'
};
try {
version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.');
version.major = version.full[0];
version.success = true;
} catch (err) {
console.warn(
'There was an issue retrieving Bootstrap\'s version. ' +
'Ensure Bootstrap is being loaded before bootstrap-select and there is no namespace collision. ' +
'If loading Bootstrap asynchronously, the version may need to be manually specified via $.fn.selectpicker.Constructor.BootstrapVersion.',
err
);
}
var selectId = 0;
var EVENT_KEY = '.bs.select';
var classNames = {
DISABLED: 'disabled',
DIVIDER: 'divider',
SHOW: 'open',
DROPUP: 'dropup',
MENU: 'dropdown-menu',
MENURIGHT: 'dropdown-menu-right',
MENULEFT: 'dropdown-menu-left',
// to-do: replace with more advanced template/customization options
BUTTONCLASS: 'btn-default',
POPOVERHEADER: 'popover-title'
}
var Selector = {
MENU: '.' + classNames.MENU
}
if (version.major === '4') {
classNames.DIVIDER = 'dropdown-divider';
classNames.SHOW = 'show';
classNames.BUTTONCLASS = 'btn-light';
classNames.POPOVERHEADER = 'popover-header';
}
var elementTemplates = {
span: document.createElement('span'),
i: document.createElement('i'),
subtext: document.createElement('small'),
a: document.createElement('a'),
li: document.createElement('li'),
whitespace: document.createTextNode('\u00A0'),
fragment: document.createDocumentFragment()
}
elementTemplates.a.setAttribute('role', 'option');
elementTemplates.subtext.className = 'text-muted';
elementTemplates.text = elementTemplates.span.cloneNode(false);
elementTemplates.text.className = 'text';
var REGEXP_ARROW = new RegExp(keyCodes.ARROW_UP + '|' + keyCodes.ARROW_DOWN);
var REGEXP_TAB_OR_ESCAPE = new RegExp('^' + keyCodes.TAB + '$|' + keyCodes.ESCAPE);
var generateOption = {
li: function (content, classes, optgroup) {
var li = elementTemplates.li.cloneNode(false);
if (content) {
if (content.nodeType === 1 || content.nodeType === 11) {
li.appendChild(content);
} else {
li.innerHTML = content;
}
}
if (typeof classes !== 'undefined' && classes !== '') li.className = classes;
if (typeof optgroup !== 'undefined' && optgroup !== null) li.classList.add('optgroup-' + optgroup);
return li;
},
a: function (text, classes, inline) {
var a = elementTemplates.a.cloneNode(true);
if (text) {
if (text.nodeType === 11) {
a.appendChild(text);
} else {
a.insertAdjacentHTML('beforeend', text);
}
}
if (typeof classes !== 'undefined' && classes !== '') a.className = classes;
if (version.major === '4') a.classList.add('dropdown-item');
if (inline) a.setAttribute('style', inline);
return a;
},
text: function (options, useFragment) {
var textElement = elementTemplates.text.cloneNode(false),
optionSubtextElement,
optionIconElement;
if (options.optionContent) {
textElement.innerHTML = options.optionContent;
} else {
textElement.textContent = options.text;
if (options.optionIcon) {
var whitespace = elementTemplates.whitespace.cloneNode(false);
// need to use for icons in the button to prevent a breaking change
// note: switch to span in next major release
optionIconElement = (useFragment === true ? elementTemplates.i : elementTemplates.span).cloneNode(false);
optionIconElement.className = options.iconBase + ' ' + options.optionIcon;
elementTemplates.fragment.appendChild(optionIconElement);
elementTemplates.fragment.appendChild(whitespace);
}
if (options.optionSubtext) {
optionSubtextElement = elementTemplates.subtext.cloneNode(false);
optionSubtextElement.textContent = options.optionSubtext;
textElement.appendChild(optionSubtextElement);
}
}
if (useFragment === true) {
while (textElement.childNodes.length > 0) {
elementTemplates.fragment.appendChild(textElement.childNodes[0]);
}
} else {
elementTemplates.fragment.appendChild(textElement);
}
return elementTemplates.fragment;
},
label: function (options) {
var labelTextElement = elementTemplates.text.cloneNode(false),
labelSubtextElement,
labelIconElement;
labelTextElement.innerHTML = options.labelEscaped;
if (options.labelIcon) {
var whitespace = elementTemplates.whitespace.cloneNode(false);
labelIconElement = elementTemplates.span.cloneNode(false);
labelIconElement.className = options.iconBase + ' ' + options.labelIcon;
elementTemplates.fragment.appendChild(labelIconElement);
elementTemplates.fragment.appendChild(whitespace);
}
if (options.labelSubtext) {
labelSubtextElement = elementTemplates.subtext.cloneNode(false);
labelSubtextElement.textContent = options.labelSubtext;
labelTextElement.appendChild(labelSubtextElement);
}
elementTemplates.fragment.appendChild(labelTextElement);
return elementTemplates.fragment;
}
}
var Selectpicker = function (element, options) {
var that = this;
// bootstrap-select has been initialized - revert valHooks.select.set back to its original function
if (!valHooks.useDefault) {
$.valHooks.select.set = valHooks._set;
valHooks.useDefault = true;
}
this.$element = $(element);
this.$newElement = null;
this.$button = null;
this.$menu = null;
this.options = options;
this.selectpicker = {
main: {
// store originalIndex (key) and newIndex (value) in this.selectpicker.main.map.newIndex for fast accessibility
// allows us to do this.main.elements[this.selectpicker.main.map.newIndex[index]] to select an element based on the originalIndex
map: {
newIndex: {},
originalIndex: {}
}
},
current: {
map: {}
}, // current changes if a search is in progress
search: {
map: {}
},
view: {},
keydown: {
keyHistory: '',
resetKeyHistory: {
start: function () {
return setTimeout(function () {
that.selectpicker.keydown.keyHistory = '';
}, 800);
}
}
}
};
// If we have no title yet, try to pull it from the html title attribute (jQuery doesnt' pick it up as it's not a
// data-attribute)
if (this.options.title === null) {
this.options.title = this.$element.attr('title');
}
// Format window padding
var winPad = this.options.windowPadding;
if (typeof winPad === 'number') {
this.options.windowPadding = [winPad, winPad, winPad, winPad];
}
// Expose public methods
this.val = Selectpicker.prototype.val;
this.render = Selectpicker.prototype.render;
this.refresh = Selectpicker.prototype.refresh;
this.setStyle = Selectpicker.prototype.setStyle;
this.selectAll = Selectpicker.prototype.selectAll;
this.deselectAll = Selectpicker.prototype.deselectAll;
this.destroy = Selectpicker.prototype.destroy;
this.remove = Selectpicker.prototype.remove;
this.show = Selectpicker.prototype.show;
this.hide = Selectpicker.prototype.hide;
this.init();
};
Selectpicker.VERSION = '1.13.8';
Selectpicker.BootstrapVersion = version.major;
// part of this is duplicated in i18n/defaults-en_US.js. Make sure to update both.
Selectpicker.DEFAULTS = {
noneSelectedText: 'Nothing selected',
noneResultsText: 'No results matched {0}',
countSelectedText: function (numSelected, numTotal) {
return (numSelected == 1) ? '{0} item selected' : '{0} items selected';
},
maxOptionsText: function (numAll, numGroup) {
return [
(numAll == 1) ? 'Limit reached ({n} item max)' : 'Limit reached ({n} items max)',
(numGroup == 1) ? 'Group limit reached ({n} item max)' : 'Group limit reached ({n} items max)'
];
},
selectAllText: 'Select All',
deselectAllText: 'Deselect All',
doneButton: false,
doneButtonText: 'Close',
multipleSeparator: ', ',
styleBase: 'btn',
style: classNames.BUTTONCLASS,
size: 'auto',
title: null,
selectedTextFormat: 'values',
width: false,
container: false,
hideDisabled: false,
showSubtext: false,
showIcon: true,
showContent: true,
dropupAuto: true,
header: false,
liveSearch: false,
liveSearchPlaceholder: null,
liveSearchNormalize: false,
liveSearchStyle: 'contains',
actionsBox: false,
iconBase: 'glyphicon',
tickIcon: 'glyphicon-ok',
showTick: false,
template: {
caret: ''
},
maxOptions: false,
mobile: false,
selectOnTab: false,
dropdownAlignRight: false,
windowPadding: 0,
virtualScroll: 600,
display: false,
sanitize: true,
sanitizeFn: null,
whiteList: DefaultWhitelist
};
if (version.major === '4') {
Selectpicker.DEFAULTS.style = 'btn-light';
Selectpicker.DEFAULTS.iconBase = '';
Selectpicker.DEFAULTS.tickIcon = 'bs-ok-default';
}
Selectpicker.prototype = {
constructor: Selectpicker,
init: function () {
var that = this,
id = this.$element.attr('id');
this.selectId = selectId++;
this.$element[0].classList.add('bs-select-hidden');
this.multiple = this.$element.prop('multiple');
this.autofocus = this.$element.prop('autofocus');
this.$newElement = this.createDropdown();
this.$element
.after(this.$newElement)
.prependTo(this.$newElement);
this.$button = this.$newElement.children('button');
this.$menu = this.$newElement.children(Selector.MENU);
this.$menuInner = this.$menu.children('.inner');
this.$searchbox = this.$menu.find('input');
this.$element[0].classList.remove('bs-select-hidden');
if (this.options.dropdownAlignRight === true) this.$menu[0].classList.add(classNames.MENURIGHT);
if (typeof id !== 'undefined') {
this.$button.attr('data-id', id);
}
this.checkDisabled();
this.clickListener();
if (this.options.liveSearch) this.liveSearchListener();
this.setStyle();
this.render();
this.setWidth();
if (this.options.container) {
this.selectPosition();
} else {
this.$element.on('hide' + EVENT_KEY, function () {
if (that.isVirtual()) {
// empty menu on close
var menuInner = that.$menuInner[0],
emptyMenu = menuInner.firstChild.cloneNode(false);
// replace the existing UL with an empty one - this is faster than $.empty() or innerHTML = ''
menuInner.replaceChild(emptyMenu, menuInner.firstChild);
menuInner.scrollTop = 0;
}
});
}
this.$menu.data('this', this);
this.$newElement.data('this', this);
if (this.options.mobile) this.mobile();
this.$newElement.on({
'hide.bs.dropdown': function (e) {
that.$menuInner.attr('aria-expanded', false);
that.$element.trigger('hide' + EVENT_KEY, e);
},
'hidden.bs.dropdown': function (e) {
that.$element.trigger('hidden' + EVENT_KEY, e);
},
'show.bs.dropdown': function (e) {
that.$menuInner.attr('aria-expanded', true);
that.$element.trigger('show' + EVENT_KEY, e);
},
'shown.bs.dropdown': function (e) {
that.$element.trigger('shown' + EVENT_KEY, e);
}
});
if (that.$element[0].hasAttribute('required')) {
this.$element.on('invalid', function () {
that.$button[0].classList.add('bs-invalid');
that.$element
.on('shown' + EVENT_KEY + '.invalid', function () {
that.$element
.val(that.$element.val()) // set the value to hide the validation message in Chrome when menu is opened
.off('shown' + EVENT_KEY + '.invalid');
})
.on('rendered' + EVENT_KEY, function () {
// if select is no longer invalid, remove the bs-invalid class
if (this.validity.valid) that.$button[0].classList.remove('bs-invalid');
that.$element.off('rendered' + EVENT_KEY);
});
that.$button.on('blur' + EVENT_KEY, function () {
that.$element.trigger('focus').trigger('blur');
that.$button.off('blur' + EVENT_KEY);
});
});
}
setTimeout(function () {
that.createLi();
that.$element.trigger('loaded' + EVENT_KEY);
});
},
createDropdown: function () {
// Options
// If we are multiple or showTick option is set, then add the show-tick class
var showTick = (this.multiple || this.options.showTick) ? ' show-tick' : '',
autofocus = this.autofocus ? ' autofocus' : '';
// Elements
var drop,
header = '',
searchbox = '',
actionsbox = '',
donebutton = '';
if (this.options.header) {
header =
'
' +
'' +
this.options.header +
'
';
}
if (this.options.liveSearch) {
searchbox =
'
' +
'' +
'
';
}
if (this.multiple && this.options.actionsBox) {
actionsbox =
'
' +
'
' +
'' +
'' +
'
' +
'
';
}
if (this.multiple && this.options.doneButton) {
donebutton =
'
' +
'
' +
'' +
'
' +
'
';
}
drop =
'
' +
'' +
'
' +
header +
searchbox +
actionsbox +
'
' +
'
' +
'
' +
'
' +
donebutton +
'
' +
'
';
return $(drop);
},
setPositionData: function () {
this.selectpicker.view.canHighlight = [];
for (var i = 0; i < this.selectpicker.current.data.length; i++) {
var li = this.selectpicker.current.data[i],
canHighlight = true;
if (li.type === 'divider') {
canHighlight = false;
li.height = this.sizeInfo.dividerHeight;
} else if (li.type === 'optgroup-label') {
canHighlight = false;
li.height = this.sizeInfo.dropdownHeaderHeight;
} else {
li.height = this.sizeInfo.liHeight;
}
if (li.disabled) canHighlight = false;
this.selectpicker.view.canHighlight.push(canHighlight);
li.position = (i === 0 ? 0 : this.selectpicker.current.data[i - 1].position) + li.height;
}
},
isVirtual: function () {
return (this.options.virtualScroll !== false) && (this.selectpicker.main.elements.length >= this.options.virtualScroll) || this.options.virtualScroll === true;
},
createView: function (isSearching, scrollTop) {
scrollTop = scrollTop || 0;
var that = this;
this.selectpicker.current = isSearching ? this.selectpicker.search : this.selectpicker.main;
var active = [];
var selected;
var prevActive;
this.setPositionData();
scroll(scrollTop, true);
this.$menuInner.off('scroll.createView').on('scroll.createView', function (e, updateValue) {
if (!that.noScroll) scroll(this.scrollTop, updateValue);
that.noScroll = false;
});
function scroll (scrollTop, init) {
var size = that.selectpicker.current.elements.length,
chunks = [],
chunkSize,
chunkCount,
firstChunk,
lastChunk,
currentChunk,
prevPositions,
positionIsDifferent,
previousElements,
menuIsDifferent = true,
isVirtual = that.isVirtual();
that.selectpicker.view.scrollTop = scrollTop;
if (isVirtual === true) {
// if an option that is encountered that is wider than the current menu width, update the menu width accordingly
if (that.sizeInfo.hasScrollBar && that.$menu[0].offsetWidth > that.sizeInfo.totalMenuWidth) {
that.sizeInfo.menuWidth = that.$menu[0].offsetWidth;
that.sizeInfo.totalMenuWidth = that.sizeInfo.menuWidth + that.sizeInfo.scrollBarWidth;
that.$menu.css('min-width', that.sizeInfo.menuWidth);
}
}
chunkSize = Math.ceil(that.sizeInfo.menuInnerHeight / that.sizeInfo.liHeight * 1.5); // number of options in a chunk
chunkCount = Math.round(size / chunkSize) || 1; // number of chunks
for (var i = 0; i < chunkCount; i++) {
var endOfChunk = (i + 1) * chunkSize;
if (i === chunkCount - 1) {
endOfChunk = size;
}
chunks[i] = [
(i) * chunkSize + (!i ? 0 : 1),
endOfChunk
];
if (!size) break;
if (currentChunk === undefined && scrollTop <= that.selectpicker.current.data[endOfChunk - 1].position - that.sizeInfo.menuInnerHeight) {
currentChunk = i;
}
}
if (currentChunk === undefined) currentChunk = 0;
prevPositions = [that.selectpicker.view.position0, that.selectpicker.view.position1];
// always display previous, current, and next chunks
firstChunk = Math.max(0, currentChunk - 1);
lastChunk = Math.min(chunkCount - 1, currentChunk + 1);
that.selectpicker.view.position0 = Math.max(0, chunks[firstChunk][0]) || 0;
that.selectpicker.view.position1 = Math.min(size, chunks[lastChunk][1]) || 0;
positionIsDifferent = prevPositions[0] !== that.selectpicker.view.position0 || prevPositions[1] !== that.selectpicker.view.position1;
if (that.activeIndex !== undefined) {
prevActive = that.selectpicker.current.elements[that.selectpicker.current.map.newIndex[that.prevActiveIndex]];
active = that.selectpicker.current.elements[that.selectpicker.current.map.newIndex[that.activeIndex]];
selected = that.selectpicker.current.elements[that.selectpicker.current.map.newIndex[that.selectedIndex]];
if (init) {
if (that.activeIndex !== that.selectedIndex && active && active.length) {
active.classList.remove('active');
if (active.firstChild) active.firstChild.classList.remove('active');
}
that.activeIndex = undefined;
}
if (that.activeIndex && that.activeIndex !== that.selectedIndex && selected && selected.length) {
selected.classList.remove('active');
if (selected.firstChild) selected.firstChild.classList.remove('active');
}
}
if (that.prevActiveIndex !== undefined && that.prevActiveIndex !== that.activeIndex && that.prevActiveIndex !== that.selectedIndex && prevActive && prevActive.length) {
prevActive.classList.remove('active');
if (prevActive.firstChild) prevActive.firstChild.classList.remove('active');
}
if (init || positionIsDifferent) {
previousElements = that.selectpicker.view.visibleElements ? that.selectpicker.view.visibleElements.slice() : [];
that.selectpicker.view.visibleElements = that.selectpicker.current.elements.slice(that.selectpicker.view.position0, that.selectpicker.view.position1);
that.setOptionStatus();
// if searching, check to make sure the list has actually been updated before updating DOM
// this prevents unnecessary repaints
if (isSearching || (isVirtual === false && init)) menuIsDifferent = !isEqual(previousElements, that.selectpicker.view.visibleElements);
// if virtual scroll is disabled and not searching,
// menu should never need to be updated more than once
if ((init || isVirtual === true) && menuIsDifferent) {
var menuInner = that.$menuInner[0],
menuFragment = document.createDocumentFragment(),
emptyMenu = menuInner.firstChild.cloneNode(false),
marginTop,
marginBottom,
elements = isVirtual === true ? that.selectpicker.view.visibleElements : that.selectpicker.current.elements,
position0 = isVirtual === true ? that.selectpicker.view.position0 : 0,
toSanitize = [];
// replace the existing UL with an empty one - this is faster than $.empty()
menuInner.replaceChild(emptyMenu, menuInner.firstChild);
for (var i = 0, visibleElementsLen = elements.length; i < visibleElementsLen; i++) {
var element = elements[i],
elText,
elementData;
if (that.options.sanitize) {
elText = element.lastChild;
if (elText) {
elementData = that.selectpicker.current.data[i + position0].data;
if (elementData && elementData.content && !elementData.sanitized) {
toSanitize.push(elText);
elementData.sanitized = true;
}
}
}
menuFragment.appendChild(element);
}
if (that.options.sanitize && toSanitize.length) {
sanitizeHtml(toSanitize, that.options.whiteList, that.options.sanitizeFn);
}
if (isVirtual === true) {
marginTop = (that.selectpicker.view.position0 === 0 ? 0 : that.selectpicker.current.data[that.selectpicker.view.position0 - 1].position);
marginBottom = (that.selectpicker.view.position1 > size - 1 ? 0 : that.selectpicker.current.data[size - 1].position - that.selectpicker.current.data[that.selectpicker.view.position1 - 1].position);
menuInner.firstChild.style.marginTop = marginTop + 'px';
menuInner.firstChild.style.marginBottom = marginBottom + 'px';
}
menuInner.firstChild.appendChild(menuFragment);
}
}
that.prevActiveIndex = that.activeIndex;
if (!that.options.liveSearch) {
that.$menuInner.trigger('focus');
} else if (isSearching && init) {
var index = 0,
newActive;
if (!that.selectpicker.view.canHighlight[index]) {
index = 1 + that.selectpicker.view.canHighlight.slice(1).indexOf(true);
}
newActive = that.selectpicker.view.visibleElements[index];
if (that.selectpicker.view.currentActive) {
that.selectpicker.view.currentActive.classList.remove('active');
if (that.selectpicker.view.currentActive.firstChild) that.selectpicker.view.currentActive.firstChild.classList.remove('active');
}
if (newActive) {
newActive.classList.add('active');
if (newActive.firstChild) newActive.firstChild.classList.add('active');
}
that.activeIndex = that.selectpicker.current.map.originalIndex[index];
}
}
$(window)
.off('resize' + EVENT_KEY + '.' + this.selectId + '.createView')
.on('resize' + EVENT_KEY + '.' + this.selectId + '.createView', function () {
var isActive = that.$newElement.hasClass(classNames.SHOW);
if (isActive) scroll(that.$menuInner[0].scrollTop);
});
},
setPlaceholder: function () {
var updateIndex = false;
if (this.options.title && !this.multiple) {
if (!this.selectpicker.view.titleOption) this.selectpicker.view.titleOption = document.createElement('option');
// this option doesn't create a new
element, but does add a new option, so liIndex is decreased
// since newIndex is recalculated on every refresh, liIndex needs to be decreased even if the titleOption is already appended
updateIndex = true;
var element = this.$element[0],
isSelected = false,
titleNotAppended = !this.selectpicker.view.titleOption.parentNode;
if (titleNotAppended) {
// Use native JS to prepend option (faster)
this.selectpicker.view.titleOption.className = 'bs-title-option';
this.selectpicker.view.titleOption.value = '';
// Check if selected or data-selected attribute is already set on an option. If not, select the titleOption option.
// the selected item may have been changed by user or programmatically before the bootstrap select plugin runs,
// if so, the select will have the data-selected attribute
var $opt = $(element.options[element.selectedIndex]);
isSelected = $opt.attr('selected') === undefined && this.$element.data('selected') === undefined;
}
if (titleNotAppended || this.selectpicker.view.titleOption.index !== 0) {
element.insertBefore(this.selectpicker.view.titleOption, element.firstChild);
}
// Set selected *after* appending to select,
// otherwise the option doesn't get selected in IE
// set using selectedIndex, as setting the selected attr to true here doesn't work in IE11
if (isSelected) element.selectedIndex = 0;
}
return updateIndex;
},
createLi: function () {
var that = this,
iconBase = that.options.iconBase,
optionSelector = ':not([hidden]):not([data-hidden="true"])',
checkMark,
mainElements = [],
widestOption,
widestOptionLength = 0,
mainData = [],
optID = 0,
headerIndex = 0,
liIndex = -1; // increment liIndex whenever a new
element is created to ensure newIndex is correct
if (this.options.hideDisabled) optionSelector += ':not(:disabled)';
if (that.options.showTick || that.multiple) {
checkMark = elementTemplates.span.cloneNode(false);
checkMark.className = iconBase + ' ' + that.options.tickIcon + ' check-mark';
elementTemplates.a.appendChild(checkMark);
}
if (this.setPlaceholder()) liIndex--;
var selectOptions = this.$element[0].options;
for (var index = 0, len = selectOptions.length; index < len; index++) {
var option = selectOptions[index];
liIndex++;
if (option.classList.contains('bs-title-option')) continue;
var thisData = {
content: option.getAttribute('data-content'),
tokens: option.getAttribute('data-tokens'),
subtext: option.getAttribute('data-subtext'),
icon: option.getAttribute('data-icon'),
hidden: option.getAttribute('data-hidden') === 'true',
divider: option.getAttribute('data-divider') === 'true'
};
// Get the class and text for the option
var optionClass = option.className || '',
cssText = option.style.cssText,
inline = cssText ? htmlEscape(cssText) : '',
optionContent = thisData.content,
text = option.textContent,
parent = option.parentNode,
next = option.nextElementSibling,
previous = option.previousElementSibling,
isOptgroup = parent.tagName === 'OPTGROUP',
isOptgroupDisabled = isOptgroup && parent.disabled,
isDisabled = option.disabled || isOptgroupDisabled,
prevHiddenIndex,
showDivider = previous && previous.tagName === 'OPTGROUP',
textElement,
labelElement,
prevHidden;
var parentData = {
hidden: parent.getAttribute('data-hidden') === 'true'
};
if (
(
(thisData.hidden === true || option.hidden) ||
(isOptgroup && (parentData.hidden === true || parent.hidden))
) ||
(that.options.hideDisabled && (isDisabled || isOptgroupDisabled))
) {
// set prevHiddenIndex - the index of the first hidden option in a group of hidden options
// used to determine whether or not a divider should be placed after an optgroup if there are
// hidden options between the optgroup and the first visible option
prevHiddenIndex = option.prevHiddenIndex;
if (next) next.prevHiddenIndex = (prevHiddenIndex !== undefined ? prevHiddenIndex : index);
liIndex--;
continue;
} else {
if (next && next.prevHiddenIndex !== undefined) next.prevHiddenIndex = undefined;
}
if (isOptgroup && thisData.divider !== true) {
var optGroupClass = ' ' + parent.className || '',
previousOption = option.previousElementSibling;
prevHiddenIndex = option.prevHiddenIndex;
// Get the first visible option before the first hidden option in the group.
// Ensures a divider is shown if, for example, the first option in the optgroup is hidden.
if (prevHiddenIndex !== undefined) {
previousOption = selectOptions[prevHiddenIndex].previousElementSibling;
}
// if there is no previous option, this option is the first visible option in the optgroup
if (!previousOption) {
optID += 1;
parentData.subtext = parent.getAttribute('data-subtext');
parentData.icon = parent.getAttribute('data-icon');
// Get the opt group label
var label = parent.label,
labelEscaped = htmlEscape(label),
labelSubtext = parentData.subtext,
labelIcon = parentData.icon;
if (index !== 0 && mainElements.length > 0) { // Is it NOT the first option of the select && are there elements in the dropdown?
liIndex++;
mainElements.push(
generateOption.li(
false,
classNames.DIVIDER,
optID + 'div'
)
);
mainData.push({
type: 'divider',
optID: optID
});
}
liIndex++;
labelElement = generateOption.label({
labelEscaped: labelEscaped,
labelSubtext: labelSubtext,
labelIcon: labelIcon,
iconBase: iconBase
});
mainElements.push(generateOption.li(labelElement, 'dropdown-header' + optGroupClass, optID));
mainData.push({
content: labelEscaped,
subtext: labelSubtext,
type: 'optgroup-label',
optID: optID
});
headerIndex = liIndex - 1;
}
textElement = generateOption.text({
text: text,
optionContent: optionContent,
optionSubtext: thisData.subtext,
optionIcon: thisData.icon,
iconBase: iconBase
});
mainElements.push(generateOption.li(generateOption.a(textElement, 'opt ' + optionClass + optGroupClass, inline), '', optID));
mainData.push({
content: optionContent || text,
subtext: thisData.subtext,
tokens: thisData.tokens,
type: 'option',
optID: optID,
headerIndex: headerIndex,
lastIndex: headerIndex + parent.querySelectorAll('option' + optionSelector).length,
originalIndex: index,
data: thisData
});
} else if (thisData.divider === true) {
mainElements.push(generateOption.li(false, classNames.DIVIDER));
mainData.push({
type: 'divider',
originalIndex: index,
data: thisData
});
} else {
if (that.options.hideDisabled) {
if (showDivider) {
var disabledOptions = previous.querySelectorAll('option:disabled');
if (disabledOptions.length === previous.children.length) showDivider = false;
} else {
prevHiddenIndex = option.prevHiddenIndex;
if (prevHiddenIndex !== undefined) {
// select the element **before** the first hidden element in the group
prevHidden = selectOptions[prevHiddenIndex].previousElementSibling;
if (prevHidden && prevHidden.tagName === 'OPTGROUP' && !prevHidden.disabled) {
var disabledOptions = prevHidden.querySelectorAll('option:disabled');
if (disabledOptions.length < prevHidden.children.length) showDivider = true;
}
}
}
}
if (showDivider && mainData.length && mainData[mainData.length - 1].type !== 'divider') {
liIndex++;
mainElements.push(
generateOption.li(
false,
classNames.DIVIDER,
optID + 'div'
)
);
mainData.push({
type: 'divider',
optID: optID
});
}
textElement = generateOption.text({
text: text,
optionContent: optionContent,
optionSubtext: thisData.subtext,
optionIcon: thisData.icon,
iconBase: iconBase
});
mainElements.push(generateOption.li(generateOption.a(textElement, optionClass, inline)));
mainData.push({
content: optionContent || text,
subtext: thisData.subtext,
tokens: thisData.tokens,
type: 'option',
originalIndex: index,
data: thisData
});
}
that.selectpicker.main.map.newIndex[index] = liIndex;
that.selectpicker.main.map.originalIndex[liIndex] = index;
// get the most recent option info added to mainData
var _mainDataLast = mainData[mainData.length - 1];
_mainDataLast.disabled = isDisabled;
var combinedLength = 0;
// count the number of characters in the option - not perfect, but should work in most cases
if (_mainDataLast.content) combinedLength += _mainDataLast.content.length;
if (_mainDataLast.subtext) combinedLength += _mainDataLast.subtext.length;
// if there is an icon, ensure this option's width is checked
if (thisData.icon) combinedLength += 1;
if (combinedLength > widestOptionLength) {
widestOptionLength = combinedLength;
// guess which option is the widest
// use this when calculating menu width
// not perfect, but it's fast, and the width will be updating accordingly when scrolling
widestOption = mainElements[mainElements.length - 1];
}
}
this.selectpicker.main.elements = mainElements;
this.selectpicker.main.data = mainData;
this.selectpicker.current = this.selectpicker.main;
this.selectpicker.view.widestOption = widestOption;
},
findLis: function () {
return this.$menuInner.find('.inner > li');
},
render: function () {
// ensure titleOption is appended and selected (if necessary) before getting selectedOptions
this.setPlaceholder();
var that = this,
selectedOptions = this.$element[0].selectedOptions,
selectedCount = selectedOptions.length,
button = this.$button[0],
buttonInner = button.querySelector('.filter-option-inner-inner'),
multipleSeparator = document.createTextNode(this.options.multipleSeparator),
titleFragment = elementTemplates.fragment.cloneNode(false),
showCount,
countMax,
hasContent = false;
this.togglePlaceholder();
this.tabIndex();
if (this.options.selectedTextFormat === 'static') {
titleFragment = generateOption.text({ text: this.options.title }, true);
} else {
showCount = this.multiple && this.options.selectedTextFormat.indexOf('count') !== -1 && selectedCount > 1;
// determine if the number of selected options will be shown (showCount === true)
if (showCount) {
countMax = this.options.selectedTextFormat.split('>');
showCount = (countMax.length > 1 && selectedCount > countMax[1]) || (countMax.length === 1 && selectedCount >= 2);
}
// only loop through all selected options if the count won't be shown
if (showCount === false) {
for (var selectedIndex = 0; selectedIndex < selectedCount; selectedIndex++) {
if (selectedIndex < 50) {
var option = selectedOptions[selectedIndex],
titleOptions = {},
thisData = {
content: option.getAttribute('data-content'),
subtext: option.getAttribute('data-subtext'),
icon: option.getAttribute('data-icon')
};
if (this.multiple && selectedIndex > 0) {
titleFragment.appendChild(multipleSeparator.cloneNode(false));
}
if (option.title) {
titleOptions.text = option.title;
} else if (thisData.content && that.options.showContent) {
titleOptions.optionContent = thisData.content.toString();
hasContent = true;
} else {
if (that.options.showIcon) {
titleOptions.optionIcon = thisData.icon;
titleOptions.iconBase = this.options.iconBase;
}
if (that.options.showSubtext && !that.multiple && thisData.subtext) titleOptions.optionSubtext = ' ' + thisData.subtext;
titleOptions.text = option.textContent.trim();
}
titleFragment.appendChild(generateOption.text(titleOptions, true));
} else {
break;
}
}
// add ellipsis
if (selectedCount > 49) {
titleFragment.appendChild(document.createTextNode('...'));
}
} else {
var optionSelector = ':not([hidden]):not([data-hidden="true"]):not([data-divider="true"])';
if (this.options.hideDisabled) optionSelector += ':not(:disabled)';
// If this is a multiselect, and selectedTextFormat is count, then show 1 of 2 selected, etc.
var totalCount = this.$element[0].querySelectorAll('select > option' + optionSelector + ', optgroup' + optionSelector + ' option' + optionSelector).length,
tr8nText = (typeof this.options.countSelectedText === 'function') ? this.options.countSelectedText(selectedCount, totalCount) : this.options.countSelectedText;
titleFragment = generateOption.text({
text: tr8nText.replace('{0}', selectedCount.toString()).replace('{1}', totalCount.toString())
}, true);
}
}
if (this.options.title == undefined) {
// use .attr to ensure undefined is returned if title attribute is not set
this.options.title = this.$element.attr('title');
}
// If the select doesn't have a title, then use the default, or if nothing is set at all, use noneSelectedText
if (!titleFragment.childNodes.length) {
titleFragment = generateOption.text({
text: typeof this.options.title !== 'undefined' ? this.options.title : this.options.noneSelectedText
}, true);
}
// strip all HTML tags and trim the result, then unescape any escaped tags
button.title = titleFragment.textContent.replace(/<[^>]*>?/g, '').trim();
if (this.options.sanitize && hasContent) {
sanitizeHtml([titleFragment], that.options.whiteList, that.options.sanitizeFn);
}
buttonInner.innerHTML = '';
buttonInner.appendChild(titleFragment);
if (version.major < 4 && this.$newElement[0].parentNode.classList.contains('input-group')) {
var filterExpand = button.querySelector('.filter-expand'),
clone = buttonInner.cloneNode(true);
clone.className = 'filter-expand';
if (filterExpand) {
button.replaceChild(clone, filterExpand);
} else {
button.appendChild(clone);
}
}
this.$element.trigger('rendered' + EVENT_KEY);
},
/**
* @param [style]
* @param [status]
*/
setStyle: function (newStyle, status) {
var button = this.$button[0],
style = this.options.style.split(' '),
buttonClass;
if (this.$element.attr('class')) {
this.$newElement.addClass(this.$element.attr('class').replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi, ''));
}
if (version.major < 4) {
this.$newElement[0].classList.add('bs3');
}
if (newStyle) {
buttonClass = newStyle.split(' ');
} else {
buttonClass = style;
}
if (status == 'add') {
button.classList.add.apply(button.classList, buttonClass);
} else if (status == 'remove') {
button.classList.remove.apply(button.classList, buttonClass);
} else {
button.classList.remove.apply(button.classList, style);
button.classList.add.apply(button.classList, buttonClass);
}
},
liHeight: function (refresh) {
if (!refresh && (this.options.size === false || this.sizeInfo)) return;
if (!this.sizeInfo) this.sizeInfo = {};
var newElement = document.createElement('div'),
menu = document.createElement('div'),
menuInner = document.createElement('div'),
menuInnerInner = document.createElement('ul'),
divider = document.createElement('li'),
dropdownHeader = document.createElement('li'),
li = document.createElement('li'),
a = document.createElement('a'),
text = document.createElement('span'),
header = this.options.header && this.$menu.find('.' + classNames.POPOVERHEADER).length > 0 ? this.$menu.find('.' + classNames.POPOVERHEADER)[0].cloneNode(true) : null,
search = this.options.liveSearch ? document.createElement('div') : null,
actions = this.options.actionsBox && this.multiple && this.$menu.find('.bs-actionsbox').length > 0 ? this.$menu.find('.bs-actionsbox')[0].cloneNode(true) : null,
doneButton = this.options.doneButton && this.multiple && this.$menu.find('.bs-donebutton').length > 0 ? this.$menu.find('.bs-donebutton')[0].cloneNode(true) : null,
firstOption = this.$element.find('option')[0];
this.sizeInfo.selectWidth = this.$newElement[0].offsetWidth;
text.className = 'text';
a.className = 'dropdown-item ' + (firstOption ? firstOption.className : '');
newElement.className = this.$menu[0].parentNode.className + ' ' + classNames.SHOW;
newElement.style.width = this.sizeInfo.selectWidth + 'px';
if (this.options.width === 'auto') menu.style.minWidth = 0;
menu.className = classNames.MENU + ' ' + classNames.SHOW;
menuInner.className = 'inner ' + classNames.SHOW;
menuInnerInner.className = classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : '');
divider.className = classNames.DIVIDER;
dropdownHeader.className = 'dropdown-header';
text.appendChild(document.createTextNode('\u200b'));
a.appendChild(text);
li.appendChild(a);
dropdownHeader.appendChild(text.cloneNode(true));
if (this.selectpicker.view.widestOption) {
menuInnerInner.appendChild(this.selectpicker.view.widestOption.cloneNode(true));
}
menuInnerInner.appendChild(li);
menuInnerInner.appendChild(divider);
menuInnerInner.appendChild(dropdownHeader);
if (header) menu.appendChild(header);
if (search) {
var input = document.createElement('input');
search.className = 'bs-searchbox';
input.className = 'form-control';
search.appendChild(input);
menu.appendChild(search);
}
if (actions) menu.appendChild(actions);
menuInner.appendChild(menuInnerInner);
menu.appendChild(menuInner);
if (doneButton) menu.appendChild(doneButton);
newElement.appendChild(menu);
document.body.appendChild(newElement);
var liHeight = li.offsetHeight,
dropdownHeaderHeight = dropdownHeader ? dropdownHeader.offsetHeight : 0,
headerHeight = header ? header.offsetHeight : 0,
searchHeight = search ? search.offsetHeight : 0,
actionsHeight = actions ? actions.offsetHeight : 0,
doneButtonHeight = doneButton ? doneButton.offsetHeight : 0,
dividerHeight = $(divider).outerHeight(true),
// fall back to jQuery if getComputedStyle is not supported
menuStyle = window.getComputedStyle ? window.getComputedStyle(menu) : false,
menuWidth = menu.offsetWidth,
$menu = menuStyle ? null : $(menu),
menuPadding = {
vert: toInteger(menuStyle ? menuStyle.paddingTop : $menu.css('paddingTop')) +
toInteger(menuStyle ? menuStyle.paddingBottom : $menu.css('paddingBottom')) +
toInteger(menuStyle ? menuStyle.borderTopWidth : $menu.css('borderTopWidth')) +
toInteger(menuStyle ? menuStyle.borderBottomWidth : $menu.css('borderBottomWidth')),
horiz: toInteger(menuStyle ? menuStyle.paddingLeft : $menu.css('paddingLeft')) +
toInteger(menuStyle ? menuStyle.paddingRight : $menu.css('paddingRight')) +
toInteger(menuStyle ? menuStyle.borderLeftWidth : $menu.css('borderLeftWidth')) +
toInteger(menuStyle ? menuStyle.borderRightWidth : $menu.css('borderRightWidth'))
},
menuExtras = {
vert: menuPadding.vert +
toInteger(menuStyle ? menuStyle.marginTop : $menu.css('marginTop')) +
toInteger(menuStyle ? menuStyle.marginBottom : $menu.css('marginBottom')) + 2,
horiz: menuPadding.horiz +
toInteger(menuStyle ? menuStyle.marginLeft : $menu.css('marginLeft')) +
toInteger(menuStyle ? menuStyle.marginRight : $menu.css('marginRight')) + 2
},
scrollBarWidth;
menuInner.style.overflowY = 'scroll';
scrollBarWidth = menu.offsetWidth - menuWidth;
document.body.removeChild(newElement);
this.sizeInfo.liHeight = liHeight;
this.sizeInfo.dropdownHeaderHeight = dropdownHeaderHeight;
this.sizeInfo.headerHeight = headerHeight;
this.sizeInfo.searchHeight = searchHeight;
this.sizeInfo.actionsHeight = actionsHeight;
this.sizeInfo.doneButtonHeight = doneButtonHeight;
this.sizeInfo.dividerHeight = dividerHeight;
this.sizeInfo.menuPadding = menuPadding;
this.sizeInfo.menuExtras = menuExtras;
this.sizeInfo.menuWidth = menuWidth;
this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth;
this.sizeInfo.scrollBarWidth = scrollBarWidth;
this.sizeInfo.selectHeight = this.$newElement[0].offsetHeight;
this.setPositionData();
},
getSelectPosition: function () {
var that = this,
$window = $(window),
pos = that.$newElement.offset(),
$container = $(that.options.container),
containerPos;
if (that.options.container && $container.length && !$container.is('body')) {
containerPos = $container.offset();
containerPos.top += parseInt($container.css('borderTopWidth'));
containerPos.left += parseInt($container.css('borderLeftWidth'));
} else {
containerPos = { top: 0, left: 0 };
}
var winPad = that.options.windowPadding;
this.sizeInfo.selectOffsetTop = pos.top - containerPos.top - $window.scrollTop();
this.sizeInfo.selectOffsetBot = $window.height() - this.sizeInfo.selectOffsetTop - this.sizeInfo.selectHeight - containerPos.top - winPad[2];
this.sizeInfo.selectOffsetLeft = pos.left - containerPos.left - $window.scrollLeft();
this.sizeInfo.selectOffsetRight = $window.width() - this.sizeInfo.selectOffsetLeft - this.sizeInfo.selectWidth - containerPos.left - winPad[1];
this.sizeInfo.selectOffsetTop -= winPad[0];
this.sizeInfo.selectOffsetLeft -= winPad[3];
},
setMenuSize: function (isAuto) {
this.getSelectPosition();
var selectWidth = this.sizeInfo.selectWidth,
liHeight = this.sizeInfo.liHeight,
headerHeight = this.sizeInfo.headerHeight,
searchHeight = this.sizeInfo.searchHeight,
actionsHeight = this.sizeInfo.actionsHeight,
doneButtonHeight = this.sizeInfo.doneButtonHeight,
divHeight = this.sizeInfo.dividerHeight,
menuPadding = this.sizeInfo.menuPadding,
menuInnerHeight,
menuHeight,
divLength = 0,
minHeight,
_minHeight,
maxHeight,
menuInnerMinHeight,
estimate;
if (this.options.dropupAuto) {
// Get the estimated height of the menu without scrollbars.
// This is useful for smaller menus, where there might be plenty of room
// below the button without setting dropup, but we can't know
// the exact height of the menu until createView is called later
estimate = liHeight * this.selectpicker.current.elements.length + menuPadding.vert;
this.$newElement.toggleClass(classNames.DROPUP, this.sizeInfo.selectOffsetTop - this.sizeInfo.selectOffsetBot > this.sizeInfo.menuExtras.vert && estimate + this.sizeInfo.menuExtras.vert + 50 > this.sizeInfo.selectOffsetBot);
}
if (this.options.size === 'auto') {
_minHeight = this.selectpicker.current.elements.length > 3 ? this.sizeInfo.liHeight * 3 + this.sizeInfo.menuExtras.vert - 2 : 0;
menuHeight = this.sizeInfo.selectOffsetBot - this.sizeInfo.menuExtras.vert;
minHeight = _minHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
menuInnerMinHeight = Math.max(_minHeight - menuPadding.vert, 0);
if (this.$newElement.hasClass(classNames.DROPUP)) {
menuHeight = this.sizeInfo.selectOffsetTop - this.sizeInfo.menuExtras.vert;
}
maxHeight = menuHeight;
menuInnerHeight = menuHeight - headerHeight - searchHeight - actionsHeight - doneButtonHeight - menuPadding.vert;
} else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
for (var i = 0; i < this.options.size; i++) {
if (this.selectpicker.current.data[i].type === 'divider') divLength++;
}
menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding.vert;
menuInnerHeight = menuHeight - menuPadding.vert;
maxHeight = menuHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
minHeight = menuInnerMinHeight = '';
}
if (this.options.dropdownAlignRight === 'auto') {
this.$menu.toggleClass(classNames.MENURIGHT, this.sizeInfo.selectOffsetLeft > this.sizeInfo.selectOffsetRight && this.sizeInfo.selectOffsetRight < (this.sizeInfo.totalMenuWidth - selectWidth));
}
this.$menu.css({
'max-height': maxHeight + 'px',
'overflow': 'hidden',
'min-height': minHeight + 'px'
});
this.$menuInner.css({
'max-height': menuInnerHeight + 'px',
'overflow-y': 'auto',
'min-height': menuInnerMinHeight + 'px'
});
// ensure menuInnerHeight is always a positive number to prevent issues calculating chunkSize in createView
this.sizeInfo.menuInnerHeight = Math.max(menuInnerHeight, 1);
if (this.selectpicker.current.data.length && this.selectpicker.current.data[this.selectpicker.current.data.length - 1].position > this.sizeInfo.menuInnerHeight) {
this.sizeInfo.hasScrollBar = true;
this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth + this.sizeInfo.scrollBarWidth;
this.$menu.css('min-width', this.sizeInfo.totalMenuWidth);
}
if (this.dropdown && this.dropdown._popper) this.dropdown._popper.update();
},
setSize: function (refresh) {
this.liHeight(refresh);
if (this.options.header) this.$menu.css('padding-top', 0);
if (this.options.size === false) return;
var that = this,
$window = $(window),
selectedIndex,
offset = 0;
this.setMenuSize();
if (this.options.liveSearch) {
this.$searchbox
.off('input.setMenuSize propertychange.setMenuSize')
.on('input.setMenuSize propertychange.setMenuSize', function () {
return that.setMenuSize();
});
}
if (this.options.size === 'auto') {
$window
.off('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize')
.on('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize', function () {
return that.setMenuSize();
});
} else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
$window.off('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize');
}
if (refresh) {
offset = this.$menuInner[0].scrollTop;
} else if (!that.multiple) {
selectedIndex = that.selectpicker.main.map.newIndex[that.$element[0].selectedIndex];
if (typeof selectedIndex === 'number' && that.options.size !== false) {
offset = that.sizeInfo.liHeight * selectedIndex;
offset = offset - (that.sizeInfo.menuInnerHeight / 2) + (that.sizeInfo.liHeight / 2);
}
}
that.createView(false, offset);
},
setWidth: function () {
var that = this;
if (this.options.width === 'auto') {
requestAnimationFrame(function () {
that.$menu.css('min-width', '0');
that.$element.on('loaded' + EVENT_KEY, function () {
that.liHeight();
that.setMenuSize();
// Get correct width if element is hidden
var $selectClone = that.$newElement.clone().appendTo('body'),
btnWidth = $selectClone.css('width', 'auto').children('button').outerWidth();
$selectClone.remove();
// Set width to whatever's larger, button title or longest option
that.sizeInfo.selectWidth = Math.max(that.sizeInfo.totalMenuWidth, btnWidth);
that.$newElement.css('width', that.sizeInfo.selectWidth + 'px');
});
});
} else if (this.options.width === 'fit') {
// Remove inline min-width so width can be changed from 'auto'
this.$menu.css('min-width', '');
this.$newElement.css('width', '').addClass('fit-width');
} else if (this.options.width) {
// Remove inline min-width so width can be changed from 'auto'
this.$menu.css('min-width', '');
this.$newElement.css('width', this.options.width);
} else {
// Remove inline min-width/width so width can be changed
this.$menu.css('min-width', '');
this.$newElement.css('width', '');
}
// Remove fit-width class if width is changed programmatically
if (this.$newElement.hasClass('fit-width') && this.options.width !== 'fit') {
this.$newElement[0].classList.remove('fit-width');
}
},
selectPosition: function () {
this.$bsContainer = $('');
var that = this,
$container = $(this.options.container),
pos,
containerPos,
actualHeight,
getPlacement = function ($element) {
var containerPosition = {},
// fall back to dropdown's default display setting if display is not manually set
display = that.options.display || (
// Bootstrap 3 doesn't have $.fn.dropdown.Constructor.Default
$.fn.dropdown.Constructor.Default ? $.fn.dropdown.Constructor.Default.display
: false
);
that.$bsContainer.addClass($element.attr('class').replace(/form-control|fit-width/gi, '')).toggleClass(classNames.DROPUP, $element.hasClass(classNames.DROPUP));
pos = $element.offset();
if (!$container.is('body')) {
containerPos = $container.offset();
containerPos.top += parseInt($container.css('borderTopWidth')) - $container.scrollTop();
containerPos.left += parseInt($container.css('borderLeftWidth')) - $container.scrollLeft();
} else {
containerPos = { top: 0, left: 0 };
}
actualHeight = $element.hasClass(classNames.DROPUP) ? 0 : $element[0].offsetHeight;
// Bootstrap 4+ uses Popper for menu positioning
if (version.major < 4 || display === 'static') {
containerPosition.top = pos.top - containerPos.top + actualHeight;
containerPosition.left = pos.left - containerPos.left;
}
containerPosition.width = $element[0].offsetWidth;
that.$bsContainer.css(containerPosition);
};
this.$button.on('click.bs.dropdown.data-api', function () {
if (that.isDisabled()) {
return;
}
getPlacement(that.$newElement);
that.$bsContainer
.appendTo(that.options.container)
.toggleClass(classNames.SHOW, !that.$button.hasClass(classNames.SHOW))
.append(that.$menu);
});
$(window)
.off('resize' + EVENT_KEY + '.' + this.selectId + ' scroll' + EVENT_KEY + '.' + this.selectId)
.on('resize' + EVENT_KEY + '.' + this.selectId + ' scroll' + EVENT_KEY + '.' + this.selectId, function () {
var isActive = that.$newElement.hasClass(classNames.SHOW);
if (isActive) getPlacement(that.$newElement);
});
this.$element.on('hide' + EVENT_KEY, function () {
that.$menu.data('height', that.$menu.height());
that.$bsContainer.detach();
});
},
setOptionStatus: function () {
var that = this,
selectOptions = this.$element[0].options;
that.noScroll = false;
if (that.selectpicker.view.visibleElements && that.selectpicker.view.visibleElements.length) {
for (var i = 0; i < that.selectpicker.view.visibleElements.length; i++) {
var index = that.selectpicker.current.map.originalIndex[i + that.selectpicker.view.position0], // faster than $(li).data('originalIndex')
option = selectOptions[index];
if (option) {
var liIndex = this.selectpicker.main.map.newIndex[index],
li = this.selectpicker.main.elements[liIndex];
that.setDisabled(
index,
option.disabled || (option.parentNode.tagName === 'OPTGROUP' && option.parentNode.disabled),
liIndex,
li
);
that.setSelected(
index,
option.selected,
liIndex,
li
);
}
}
}
},
/**
* @param {number} index - the index of the option that is being changed
* @param {boolean} selected - true if the option is being selected, false if being deselected
*/
setSelected: function (index, selected, liIndex, li) {
var activeIndexIsSet = this.activeIndex !== undefined,
thisIsActive = this.activeIndex === index,
prevActiveIndex,
prevActive,
a,
// if current option is already active
// OR
// if the current option is being selected, it's NOT multiple, and
// activeIndex is undefined:
// - when the menu is first being opened, OR
// - after a search has been performed, OR
// - when retainActive is false when selecting a new option (i.e. index of the newly selected option is not the same as the current activeIndex)
keepActive = thisIsActive || (selected && !this.multiple && !activeIndexIsSet);
if (!liIndex) liIndex = this.selectpicker.main.map.newIndex[index];
if (!li) li = this.selectpicker.main.elements[liIndex];
a = li.firstChild;
if (selected) {
this.selectedIndex = index;
}
li.classList.toggle('selected', selected);
li.classList.toggle('active', keepActive);
if (keepActive) {
this.selectpicker.view.currentActive = li;
this.activeIndex = index;
}
if (a) {
a.classList.toggle('selected', selected);
a.classList.toggle('active', keepActive);
a.setAttribute('aria-selected', selected);
}
if (!keepActive) {
if (!activeIndexIsSet && selected && this.prevActiveIndex !== undefined) {
prevActiveIndex = this.selectpicker.main.map.newIndex[this.prevActiveIndex];
prevActive = this.selectpicker.main.elements[prevActiveIndex];
prevActive.classList.remove('active');
if (prevActive.firstChild) {
prevActive.firstChild.classList.remove('active');
}
}
}
},
/**
* @param {number} index - the index of the option that is being disabled
* @param {boolean} disabled - true if the option is being disabled, false if being enabled
*/
setDisabled: function (index, disabled, liIndex, li) {
var a;
if (!liIndex) liIndex = this.selectpicker.main.map.newIndex[index];
if (!li) li = this.selectpicker.main.elements[liIndex];
a = li.firstChild;
li.classList.toggle(classNames.DISABLED, disabled);
if (a) {
if (version.major === '4') a.classList.toggle(classNames.DISABLED, disabled);
a.setAttribute('aria-disabled', disabled);
if (disabled) {
a.setAttribute('tabindex', -1);
} else {
a.setAttribute('tabindex', 0);
}
}
},
isDisabled: function () {
return this.$element[0].disabled;
},
checkDisabled: function () {
var that = this;
if (this.isDisabled()) {
this.$newElement[0].classList.add(classNames.DISABLED);
this.$button.addClass(classNames.DISABLED).attr('tabindex', -1).attr('aria-disabled', true);
} else {
if (this.$button[0].classList.contains(classNames.DISABLED)) {
this.$newElement[0].classList.remove(classNames.DISABLED);
this.$button.removeClass(classNames.DISABLED).attr('aria-disabled', false);
}
if (this.$button.attr('tabindex') == -1 && !this.$element.data('tabindex')) {
this.$button.removeAttr('tabindex');
}
}
this.$button.on('click', function () {
return !that.isDisabled();
});
},
togglePlaceholder: function () {
// much faster than calling $.val()
var element = this.$element[0],
selectedIndex = element.selectedIndex,
nothingSelected = selectedIndex === -1;
if (!nothingSelected && !element.options[selectedIndex].value) nothingSelected = true;
this.$button.toggleClass('bs-placeholder', nothingSelected);
},
tabIndex: function () {
if (this.$element.data('tabindex') !== this.$element.attr('tabindex') &&
(this.$element.attr('tabindex') !== -98 && this.$element.attr('tabindex') !== '-98')) {
this.$element.data('tabindex', this.$element.attr('tabindex'));
this.$button.attr('tabindex', this.$element.data('tabindex'));
}
this.$element.attr('tabindex', -98);
},
clickListener: function () {
var that = this,
$document = $(document);
$document.data('spaceSelect', false);
this.$button.on('keyup', function (e) {
if (/(32)/.test(e.keyCode.toString(10)) && $document.data('spaceSelect')) {
e.preventDefault();
$document.data('spaceSelect', false);
}
});
this.$newElement.on('show.bs.dropdown', function () {
if (version.major > 3 && !that.dropdown) {
that.dropdown = that.$button.data('bs.dropdown');
that.dropdown._menu = that.$menu[0];
}
});
this.$button.on('click.bs.dropdown.data-api', function () {
if (!that.$newElement.hasClass(classNames.SHOW)) {
that.setSize();
}
});
function setFocus () {
if (that.options.liveSearch) {
that.$searchbox.trigger('focus');
} else {
that.$menuInner.trigger('focus');
}
}
function checkPopperExists () {
if (that.dropdown && that.dropdown._popper && that.dropdown._popper.state.isCreated) {
setFocus();
} else {
requestAnimationFrame(checkPopperExists);
}
}
this.$element.on('shown' + EVENT_KEY, function () {
if (that.$menuInner[0].scrollTop !== that.selectpicker.view.scrollTop) {
that.$menuInner[0].scrollTop = that.selectpicker.view.scrollTop;
}
if (version.major > 3) {
requestAnimationFrame(checkPopperExists);
} else {
setFocus();
}
});
this.$menuInner.on('click', 'li a', function (e, retainActive) {
var $this = $(this),
position0 = that.isVirtual() ? that.selectpicker.view.position0 : 0,
clickedIndex = that.selectpicker.current.map.originalIndex[$this.parent().index() + position0],
prevValue = getSelectValues(that.$element[0]),
prevIndex = that.$element.prop('selectedIndex'),
triggerChange = true;
// Don't close on multi choice menu
if (that.multiple && that.options.maxOptions !== 1) {
e.stopPropagation();
}
e.preventDefault();
// Don't run if the select is disabled
if (!that.isDisabled() && !$this.parent().hasClass(classNames.DISABLED)) {
var $options = that.$element.find('option'),
$option = $options.eq(clickedIndex),
state = $option.prop('selected'),
$optgroup = $option.parent('optgroup'),
$optgroupOptions = $optgroup.find('option'),
maxOptions = that.options.maxOptions,
maxOptionsGrp = $optgroup.data('maxOptions') || false;
if (clickedIndex === that.activeIndex) retainActive = true;
if (!retainActive) {
that.prevActiveIndex = that.activeIndex;
that.activeIndex = undefined;
}
if (!that.multiple) { // Deselect all others if not multi select box
$options.prop('selected', false);
$option.prop('selected', true);
that.setSelected(clickedIndex, true);
} else { // Toggle the one we have chosen if we are multi select.
$option.prop('selected', !state);
that.setSelected(clickedIndex, !state);
$this.trigger('blur');
if (maxOptions !== false || maxOptionsGrp !== false) {
var maxReached = maxOptions < $options.filter(':selected').length,
maxReachedGrp = maxOptionsGrp < $optgroup.find('option:selected').length;
if ((maxOptions && maxReached) || (maxOptionsGrp && maxReachedGrp)) {
if (maxOptions && maxOptions == 1) {
$options.prop('selected', false);
$option.prop('selected', true);
for (var i = 0; i < $options.length; i++) {
that.setSelected(i, false);
}
that.setSelected(clickedIndex, true);
} else if (maxOptionsGrp && maxOptionsGrp == 1) {
$optgroup.find('option:selected').prop('selected', false);
$option.prop('selected', true);
for (var i = 0; i < $optgroupOptions.length; i++) {
var option = $optgroupOptions[i];
that.setSelected($options.index(option), false);
}
that.setSelected(clickedIndex, true);
} else {
var maxOptionsText = typeof that.options.maxOptionsText === 'string' ? [that.options.maxOptionsText, that.options.maxOptionsText] : that.options.maxOptionsText,
maxOptionsArr = typeof maxOptionsText === 'function' ? maxOptionsText(maxOptions, maxOptionsGrp) : maxOptionsText,
maxTxt = maxOptionsArr[0].replace('{n}', maxOptions),
maxTxtGrp = maxOptionsArr[1].replace('{n}', maxOptionsGrp),
$notify = $('');
// If {var} is set in array, replace it
/** @deprecated */
if (maxOptionsArr[2]) {
maxTxt = maxTxt.replace('{var}', maxOptionsArr[2][maxOptions > 1 ? 0 : 1]);
maxTxtGrp = maxTxtGrp.replace('{var}', maxOptionsArr[2][maxOptionsGrp > 1 ? 0 : 1]);
}
$option.prop('selected', false);
that.$menu.append($notify);
if (maxOptions && maxReached) {
$notify.append($('