UNPKG

bootstrap-select

Version:

The jQuery plugin that brings select elements into the 21st century with intuitive multiselection, searching, and much more. Now with Bootstrap 4 support.

1,413 lines (1,192 loc) 96.7 kB
(function ($) { 'use strict'; var testElement = document.createElement('_'); 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); } }; } // shallow array comparison function isEqual (array1, array2) { return array1.length === array2.length && array1.every(function(element, index) { return element === array2[index]; }); }; //<editor-fold desc="Shims"> 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; }; } // much faster than $.val() function getSelectValues(select) { var result = []; var options = select && select.options; var opt; if (select.multiple) { for (var i = 0, len = options.length; i < len; i++) { opt = options[i]; if (opt.selected) { 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 changed_arguments = 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); } }; //</editor-fold> 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; } /** * Remove all diatrics from the given text. * @access private * @param {String} text * @returns {String} */ function normalizeToBase(text) { var rExps = [ {re: /[\xC0-\xC6]/g, ch: "A"}, {re: /[\xE0-\xE6]/g, ch: "a"}, {re: /[\xC8-\xCB]/g, ch: "E"}, {re: /[\xE8-\xEB]/g, ch: "e"}, {re: /[\xCC-\xCF]/g, ch: "I"}, {re: /[\xEC-\xEF]/g, ch: "i"}, {re: /[\xD2-\xD6]/g, ch: "O"}, {re: /[\xF2-\xF6]/g, ch: "o"}, {re: /[\xD9-\xDC]/g, ch: "U"}, {re: /[\xF9-\xFC]/g, ch: "u"}, {re: /[\xC7-\xE7]/g, ch: "c"}, {re: /[\xD1]/g, ch: "N"}, {re: /[\xF1]/g, ch: "n"} ]; $.each(rExps, function () { text = text ? text.replace(this.re, this.ch) : ''; }); return text; } // List of HTML entities for escaping. var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; var unescapeMap = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#x27;': "'", '&#x60;': '`' }; // 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); var htmlUnescape = createEscaper(unescapeMap); /** * ------------------------------------------------------------------------ * 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 = {}; version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.'); version.major = version.full[0]; var classNames = { DISABLED: 'disabled', DIVIDER: version.major === '4' ? 'dropdown-divider' : 'divider', SHOW: version.major === '4' ? 'show' : 'open', DROPUP: 'dropup', MENURIGHT: 'dropdown-menu-right', MENULEFT: 'dropdown-menu-left', // to-do: replace with more advanced template/customization options BUTTONCLASS: version.major === '4' ? 'btn-light' : 'btn-default', POPOVERHEADER: version.major === '4' ? 'popover-header' : 'popover-title' } var REGEXP_ARROW = new RegExp(keyCodes.ARROW_UP + '|' + keyCodes.ARROW_DOWN); var REGEXP_TAB_OR_ESCAPE = new RegExp('^' + keyCodes.TAB + '$|' + keyCodes.ESCAPE); var REGEXP_ENTER_OR_SPACE = new RegExp(keyCodes.ENTER + '|' + keyCodes.SPACE); 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.0'; // 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: 'btn-default', 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: '<span class="caret"></span>' }, maxOptions: false, mobile: false, selectOnTab: false, dropdownAlignRight: false, windowPadding: 0, virtualScroll: 600 }; 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.$element.addClass('bs-select-hidden'); this.multiple = this.$element.prop('multiple'); this.autofocus = this.$element.prop('autofocus'); this.$newElement = this.createDropdown(); this.createLi(); this.$element .after(this.$newElement) .prependTo(this.$newElement); this.$button = this.$newElement.children('button'); this.$menu = this.$newElement.children('.dropdown-menu'); this.$menuInner = this.$menu.children('.inner'); this.$searchbox = this.$menu.find('input'); this.$element.removeClass('bs-select-hidden'); if (this.options.dropdownAlignRight === true) this.$menu.addClass(classNames.MENURIGHT); if (typeof id !== 'undefined') { this.$button.attr('data-id', id); } this.checkDisabled(); this.clickListener(); if (this.options.liveSearch) this.liveSearchListener(); this.render(); this.setStyle(); this.setWidth(); if (this.options.container) { this.selectPosition(); } else { this.$element.on('hide.bs.select', 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.bs.select', e); }, 'hidden.bs.dropdown': function (e) { that.$element.trigger('hidden.bs.select', e); }, 'show.bs.dropdown': function (e) { that.$menuInner.attr('aria-expanded', true); that.$element.trigger('show.bs.select', e); }, 'shown.bs.dropdown': function (e) { that.$element.trigger('shown.bs.select', e); } }); if (that.$element[0].hasAttribute('required')) { this.$element.on('invalid', function () { that.$button.addClass('bs-invalid'); that.$element.on({ 'shown.bs.select': function () { that.$element .val(that.$element.val()) // set the value to hide the validation message in Chrome when menu is opened .off('shown.bs.select'); }, 'rendered.bs.select': function () { // if select is no longer invalid, remove the bs-invalid class if (this.validity.valid) that.$button.removeClass('bs-invalid'); that.$element.off('rendered.bs.select'); } }); that.$button.on('blur.bs.select', function () { that.$element.focus().blur(); that.$button.off('blur.bs.select'); }); }); } setTimeout(function () { that.$element.trigger('loaded.bs.select'); }); }, 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 header = this.options.header ? '<div class="' + classNames.POPOVERHEADER + '"><button type="button" class="close" aria-hidden="true">&times;</button>' + this.options.header + '</div>' : ''; var searchbox = this.options.liveSearch ? '<div class="bs-searchbox">' + '<input type="text" class="form-control" autocomplete="off"' + (null === this.options.liveSearchPlaceholder ? '' : ' placeholder="' + htmlEscape(this.options.liveSearchPlaceholder) + '"') + ' role="textbox" aria-label="Search">' + '</div>' : ''; var actionsbox = this.multiple && this.options.actionsBox ? '<div class="bs-actionsbox">' + '<div class="btn-group btn-group-sm btn-block">' + '<button type="button" class="actions-btn bs-select-all btn ' + classNames.BUTTONCLASS + '">' + this.options.selectAllText + '</button>' + '<button type="button" class="actions-btn bs-deselect-all btn ' + classNames.BUTTONCLASS + '">' + this.options.deselectAllText + '</button>' + '</div>' + '</div>' : ''; var donebutton = this.multiple && this.options.doneButton ? '<div class="bs-donebutton">' + '<div class="btn-group btn-block">' + '<button type="button" class="btn btn-sm ' + classNames.BUTTONCLASS + '">' + this.options.doneButtonText + '</button>' + '</div>' + '</div>' : ''; var drop = '<div class="dropdown bootstrap-select' + showTick + '">' + '<button type="button" class="' + this.options.styleBase + ' dropdown-toggle" data-toggle="dropdown"' + autofocus + ' role="button">' + '<div class="filter-option">' + '<div class="filter-option-inner">' + '<div class="filter-option-inner-inner"></div>' + '</div> ' + '</div>' + (version.major === '4' ? '' : '<span class="bs-caret">' + this.options.template.caret + '</span>' ) + '</button>' + '<div class="dropdown-menu ' + (version.major === '4' ? '' : classNames.SHOW) + '" role="combobox">' + header + searchbox + actionsbox + '<div class="inner ' + classNames.SHOW + '" role="listbox" aria-expanded="false" tabindex="-1">' + '<ul class="dropdown-menu inner ' + (version.major === '4' ? classNames.SHOW : '') + '">' + '</ul>' + '</div>' + donebutton + '</div>' + '</div>'; 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 $lis; var active = []; var selected; var prevActive; var activeIndex; var prevActiveIndex; 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 = undefined, 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 end_of_chunk = (i + 1) * chunkSize; if (i === chunkCount - 1) { end_of_chunk = size; } chunks[i] = [ (i) * chunkSize + (!i ? 0 : 1), end_of_chunk ]; if (!size) break; if (currentChunk === undefined && scrollTop <= that.selectpicker.current.data[end_of_chunk - 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.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; // 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++) { menuFragment.appendChild(elements[i]); } 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.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.createView').on('resize.createView', function () { scroll(that.$menuInner[0].scrollTop); }); }, createLi: function () { var that = this, mainElements = [], widestOption, availableOptionsCount = 0, widestOptionLength = 0, mainData = [], optID = 0, headerIndex = 0, liIndex = -1; // increment liIndex whenever a new <li> element is created to ensure newIndex is correct if (!this.selectpicker.view.titleOption) this.selectpicker.view.titleOption = document.createElement('option'); var elementTemplates = { span: document.createElement('span'), subtext: document.createElement('small'), a: document.createElement('a'), li: document.createElement('li'), whitespace: document.createTextNode("\u00A0") }, checkMark = elementTemplates.span.cloneNode(false), fragment = document.createDocumentFragment(); checkMark.className = that.options.iconBase + ' ' + that.options.tickIcon + ' check-mark'; elementTemplates.a.appendChild(checkMark); elementTemplates.a.setAttribute('role', 'option'); elementTemplates.subtext.className = 'text-muted'; elementTemplates.text = elementTemplates.span.cloneNode(false); elementTemplates.text.className = 'text'; // Helper functions /** * @param content * @param [index] * @param [classes] * @param [optgroup] * @returns {HTMLElement} */ var generateLI = function (content, index, 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' && null !== optgroup) li.classList.add('optgroup-' + optgroup); return li; }; /** * @param text * @param [classes] * @param [inline] * @returns {string} */ var generateA = 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; }; var generateText = function (options) { 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); optionIconElement = elementTemplates.span.cloneNode(false); optionIconElement.className = that.options.iconBase + ' ' + options.optionIcon; fragment.appendChild(optionIconElement); fragment.appendChild(whitespace); } if (options.optionSubtext) { optionSubtextElement = elementTemplates.subtext.cloneNode(false); optionSubtextElement.textContent = options.optionSubtext; textElement.appendChild(optionSubtextElement); } } fragment.appendChild(textElement); return fragment; }; var generateLabel = function (options) { var labelTextElement = elementTemplates.text.cloneNode(false), labelSubtextElement, labelIconElement; labelTextElement.textContent = options.labelEscaped; if (options.labelIcon) { var whitespace = elementTemplates.whitespace.cloneNode(false); labelIconElement = elementTemplates.span.cloneNode(false); labelIconElement.className = that.options.iconBase + ' ' + options.labelIcon; fragment.appendChild(labelIconElement); fragment.appendChild(whitespace); } if (options.labelSubtext) { labelSubtextElement = elementTemplates.subtext.cloneNode(false); labelSubtextElement.textContent = options.labelSubtext; labelTextElement.appendChild(labelSubtextElement); } fragment.appendChild(labelTextElement); return fragment; } if (this.options.title && !this.multiple) { // this option doesn't create a new <li> 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 liIndex--; 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; } var $selectOptions = this.$element.find('option'); $selectOptions.each(function (index) { var $this = $(this); liIndex++; if ($this.hasClass('bs-title-option')) return; var thisData = $this.data(); // Get the class and text for the option var optionClass = this.className || '', inline = htmlEscape(this.style.cssText), optionContent = thisData.content, text = this.textContent, tokens = thisData.tokens, subtext = thisData.subtext, icon = thisData.icon, $parent = $this.parent(), parent = $parent[0], isOptgroup = parent.tagName === 'OPTGROUP', isOptgroupDisabled = isOptgroup && parent.disabled, isDisabled = this.disabled || isOptgroupDisabled, prevHiddenIndex, showDivider = this.previousElementSibling && this.previousElementSibling.tagName === 'OPTGROUP', textElement; var parentData = $parent.data(); if (thisData.hidden === true || that.options.hideDisabled && (isDisabled && !isOptgroup || 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 = thisData.prevHiddenIndex; $this.next().data('prevHiddenIndex', (prevHiddenIndex !== undefined ? prevHiddenIndex : index)); liIndex--; // if previous element is not an optgroup if (!showDivider) { if (prevHiddenIndex !== undefined) { // select the element **before** the first hidden element in the group var prevHidden = $selectOptions[prevHiddenIndex].previousElementSibling; if (prevHidden && prevHidden.tagName === 'OPTGROUP' && !prevHidden.disabled) { showDivider = true; } } } if (showDivider && mainData[mainData.length - 1].type !== 'divider') { liIndex++; mainElements.push( generateLI( false, null, classNames.DIVIDER, optID + 'div' ) ); mainData.push({ type: 'divider', optID: optID, originalIndex: index }); } return; } if (isOptgroup && thisData.divider !== true) { if (that.options.hideDisabled && isDisabled) { if (parentData.allOptionsDisabled === undefined) { var $options = $parent.children(); $parent.data('allOptionsDisabled', $options.filter(':disabled').length === $options.length); } if ($parent.data('allOptionsDisabled')) { liIndex--; return; } } var optGroupClass = ' ' + parent.className || ''; if (!this.previousElementSibling) { // Is it the first option of the optgroup? optID += 1; // 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( generateLI( false, null, classNames.DIVIDER, optID + 'div' ) ); mainData.push({ type: 'divider', optID: optID, originalIndex: index }); } liIndex++; var labelElement = generateLabel({ labelEscaped: labelEscaped, labelSubtext: labelSubtext, labelIcon: labelIcon }); mainElements.push(generateLI(labelElement, null, 'dropdown-header' + optGroupClass, optID)); mainData.push({ content: labelEscaped, subtext: labelSubtext, type: 'optgroup-label', optID: optID, originalIndex: index }); headerIndex = liIndex - 1; } if (that.options.hideDisabled && isDisabled || thisData.hidden === true) { liIndex--; return; } textElement = generateText({ text: text, optionContent: optionContent, optionSubtext: subtext, optionIcon: icon }); mainElements.push(generateLI(generateA(textElement, 'opt ' + optionClass + optGroupClass, inline), index, '', optID)); mainData.push({ content: optionContent || text, subtext: subtext, tokens: tokens, type: 'option', optID: optID, headerIndex: headerIndex, lastIndex: headerIndex + parent.childElementCount, originalIndex: index, data: thisData }); availableOptionsCount++; } else if (thisData.divider === true) { mainElements.push(generateLI(false, index, 'divider')); mainData.push({ type: 'divider', originalIndex: index }); } else { // if previous element is not an optgroup and hideDisabled is true if (!showDivider && that.options.hideDisabled) { prevHiddenIndex = thisData.prevHiddenIndex; if (prevHiddenIndex !== undefined) { // select the element **before** the first hidden element in the group var prevHidden = $selectOptions[prevHiddenIndex].previousElementSibling; if (prevHidden && prevHidden.tagName === 'OPTGROUP' && !prevHidden.disabled) { showDivider = true; } } } if (showDivider && mainData[mainData.length - 1].type !== 'divider') { liIndex++; mainElements.push( generateLI( false, null, classNames.DIVIDER, optID + 'div' ) ); mainData.push({ type: 'divider', optID: optID, originalIndex: index }); } textElement = generateText({ text: text, optionContent: optionContent, optionSubtext: subtext, optionIcon: icon }); mainElements.push(generateLI(generateA(textElement, optionClass, inline), index)); mainData.push({ content: optionContent || text, subtext: subtext, tokens: tokens, type: 'option', originalIndex: index, data: thisData }); availableOptionsCount++; } 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 (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; this.selectpicker.view.availableOptionsCount = availableOptionsCount; // faster way to get # of available options without filter }, findLis: function () { return this.$menuInner.find('.inner > li'); }, render: function () { var that = this, $selectOptions = this.$element.find('option'), selectedItems = [], selectedItemsInTitle = []; this.togglePlaceholder(); this.tabIndex(); for (var i = 0, len = this.selectpicker.main.elements.length; i < len; i++) { var index = this.selectpicker.main.map.originalIndex[i], option = $selectOptions[index]; if (option && option.selected) { selectedItems.push(option); if (selectedItemsInTitle.length < 100 && that.options.selectedTextFormat !== 'count' || selectedItems.length === 1) { if (that.options.hideDisabled && (option.disabled || option.parentNode.tagName === 'OPTGROUP' && option.parentNode.disabled)) return; var thisData = this.selectpicker.main.data[i].data, icon = thisData.icon && that.options.showIcon ? '<i class="' + that.options.iconBase + ' ' + thisData.icon + '"></i> ' : '', subtext, titleItem; if (that.options.showSubtext && thisData.subtext && !that.multiple) { subtext = ' <small class="text-muted">' + thisData.subtext + '</small>'; } else { subtext = ''; } if (option.title) { titleItem = option.title; } else if (thisData.content && that.options.showContent) { titleItem = thisData.content.toString(); } else { titleItem = icon + option.innerHTML.trim() + subtext; } selectedItemsInTitle.push(titleItem); } } } //Fixes issue in IE10 occurring when no default option is selected and at least one option is disabled //Convert all the values into a comma delimited string var title = !this.multiple ? selectedItemsInTitle[0] : selectedItemsInTitle.join(this.options.multipleSeparator); // add ellipsis if (selectedItems.length > 50) title += '...'; // If this is a multiselect, and selectedTextFormat is count, then show 1 of 2 selected etc.. if (this.multiple && this.options.selectedTextFormat.indexOf('count') !== -1) { var max = this.options.selectedTextFormat.split('>'); if ((max.length > 1 && selectedItems.length > max[1]) || (max.length === 1 && selectedItems.length >= 2)) { var totalCount = this.selectpicker.view.availableOptionsCount, tr8nText = (typeof this.options.countSelectedText === 'function') ? this.options.countSelectedText(selectedItems.length, totalCount) : this.options.countSelectedText; title = tr8nText.replace('{0}', selectedItems.length.toString()).replace('{1}', totalCount.toString()); } } if (this.options.title == undefined) { this.options.title = this.$element[0].title; } if (this.options.selectedTextFormat == 'static') { title = this.options.title; } //If we dont have a title, then use the default, or if nothing is set at all, use the not selected text if (!title) { title = typeof this.options.title !== 'undefined' ? this.options.title : this.options.noneSelectedText; } //strip all HTML tags and trim the result, then unescape any escaped tags this.$button[0].title = htmlUnescape(title.replace(/<[^>]*>?/g, '').trim()); this.$button.find('.filter-option-inner-inner')[0].innerHTML = title; this.$element.trigger('rendered.bs.select'); }, /** * @param [style] * @param [status] */ setStyle: function (style, status) { if (this.$element.attr('class')) { this.$newElement.addClass(this.$element.attr('class').replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi, '')); } var buttonClass = style ? style : this.options.style; if (status == 'add') { this.$button.addClass(buttonClass); } else if (status == 'remove') { this.$button.removeClass(buttonClass); } else { this.$button.removeClass(this.options.style); this.$button.addClass(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(