bootstrap-select.js 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139
  1. /*!
  2. * Bootstrap-select v1.13.10 (https://developer.snapappointments.com/bootstrap-select)
  3. *
  4. * Copyright 2012-2019 SnapAppointments, LLC
  5. * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
  6. */
  7. (function (root, factory) {
  8. if (root === undefined && window !== undefined) root = window;
  9. if (typeof define === 'function' && define.amd) {
  10. // AMD. Register as an anonymous module unless amdModuleId is set
  11. define(["jquery"], function (a0) {
  12. return (factory(a0));
  13. });
  14. } else if (typeof module === 'object' && module.exports) {
  15. // Node. Does not work with strict CommonJS, but
  16. // only CommonJS-like environments that support module.exports,
  17. // like Node.
  18. module.exports = factory(require("jquery"));
  19. } else {
  20. factory(root["jQuery"]);
  21. }
  22. }(this, function (jQuery) {
  23. (function ($) {
  24. 'use strict';
  25. var DISALLOWED_ATTRIBUTES = ['sanitize', 'whiteList', 'sanitizeFn'];
  26. var uriAttrs = [
  27. 'background',
  28. 'cite',
  29. 'href',
  30. 'itemtype',
  31. 'longdesc',
  32. 'poster',
  33. 'src',
  34. 'xlink:href'
  35. ];
  36. var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i;
  37. var DefaultWhitelist = {
  38. // Global attributes allowed on any supplied element below.
  39. '*': ['class', 'dir', 'id', 'lang', 'role', 'tabindex', 'style', ARIA_ATTRIBUTE_PATTERN],
  40. a: ['target', 'href', 'title', 'rel'],
  41. area: [],
  42. b: [],
  43. br: [],
  44. col: [],
  45. code: [],
  46. div: [],
  47. em: [],
  48. hr: [],
  49. h1: [],
  50. h2: [],
  51. h3: [],
  52. h4: [],
  53. h5: [],
  54. h6: [],
  55. i: [],
  56. img: ['src', 'alt', 'title', 'width', 'height'],
  57. li: [],
  58. ol: [],
  59. p: [],
  60. pre: [],
  61. s: [],
  62. small: [],
  63. span: [],
  64. sub: [],
  65. sup: [],
  66. strong: [],
  67. u: [],
  68. ul: []
  69. }
  70. /**
  71. * A pattern that recognizes a commonly useful subset of URLs that are safe.
  72. *
  73. * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
  74. */
  75. var SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi;
  76. /**
  77. * A pattern that matches safe data URLs. Only matches image, video and audio types.
  78. *
  79. * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
  80. */
  81. 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;
  82. function allowedAttribute (attr, allowedAttributeList) {
  83. var attrName = attr.nodeName.toLowerCase()
  84. if ($.inArray(attrName, allowedAttributeList) !== -1) {
  85. if ($.inArray(attrName, uriAttrs) !== -1) {
  86. return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN))
  87. }
  88. return true
  89. }
  90. var regExp = $(allowedAttributeList).filter(function (index, value) {
  91. return value instanceof RegExp
  92. })
  93. // Check if a regular expression validates the attribute.
  94. for (var i = 0, l = regExp.length; i < l; i++) {
  95. if (attrName.match(regExp[i])) {
  96. return true
  97. }
  98. }
  99. return false
  100. }
  101. function sanitizeHtml (unsafeElements, whiteList, sanitizeFn) {
  102. if (sanitizeFn && typeof sanitizeFn === 'function') {
  103. return sanitizeFn(unsafeElements);
  104. }
  105. var whitelistKeys = Object.keys(whiteList);
  106. for (var i = 0, len = unsafeElements.length; i < len; i++) {
  107. var elements = unsafeElements[i].querySelectorAll('*');
  108. for (var j = 0, len2 = elements.length; j < len2; j++) {
  109. var el = elements[j];
  110. var elName = el.nodeName.toLowerCase();
  111. if (whitelistKeys.indexOf(elName) === -1) {
  112. el.parentNode.removeChild(el);
  113. continue;
  114. }
  115. var attributeList = [].slice.call(el.attributes);
  116. var whitelistedAttributes = [].concat(whiteList['*'] || [], whiteList[elName] || []);
  117. for (var k = 0, len3 = attributeList.length; k < len3; k++) {
  118. var attr = attributeList[k];
  119. if (!allowedAttribute(attr, whitelistedAttributes)) {
  120. el.removeAttribute(attr.nodeName);
  121. }
  122. }
  123. }
  124. }
  125. }
  126. // Polyfill for browsers with no classList support
  127. // Remove in v2
  128. if (!('classList' in document.createElement('_'))) {
  129. (function (view) {
  130. if (!('Element' in view)) return;
  131. var classListProp = 'classList',
  132. protoProp = 'prototype',
  133. elemCtrProto = view.Element[protoProp],
  134. objCtr = Object,
  135. classListGetter = function () {
  136. var $elem = $(this);
  137. return {
  138. add: function (classes) {
  139. classes = Array.prototype.slice.call(arguments).join(' ');
  140. return $elem.addClass(classes);
  141. },
  142. remove: function (classes) {
  143. classes = Array.prototype.slice.call(arguments).join(' ');
  144. return $elem.removeClass(classes);
  145. },
  146. toggle: function (classes, force) {
  147. return $elem.toggleClass(classes, force);
  148. },
  149. contains: function (classes) {
  150. return $elem.hasClass(classes);
  151. }
  152. }
  153. };
  154. if (objCtr.defineProperty) {
  155. var classListPropDesc = {
  156. get: classListGetter,
  157. enumerable: true,
  158. configurable: true
  159. };
  160. try {
  161. objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
  162. } catch (ex) { // IE 8 doesn't support enumerable:true
  163. // adding undefined to fight this issue https://github.com/eligrey/classList.js/issues/36
  164. // modernie IE8-MSW7 machine has IE8 8.0.6001.18702 and is affected
  165. if (ex.number === undefined || ex.number === -0x7FF5EC54) {
  166. classListPropDesc.enumerable = false;
  167. objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
  168. }
  169. }
  170. } else if (objCtr[protoProp].__defineGetter__) {
  171. elemCtrProto.__defineGetter__(classListProp, classListGetter);
  172. }
  173. }(window));
  174. }
  175. var testElement = document.createElement('_');
  176. testElement.classList.add('c1', 'c2');
  177. if (!testElement.classList.contains('c2')) {
  178. var _add = DOMTokenList.prototype.add,
  179. _remove = DOMTokenList.prototype.remove;
  180. DOMTokenList.prototype.add = function () {
  181. Array.prototype.forEach.call(arguments, _add.bind(this));
  182. }
  183. DOMTokenList.prototype.remove = function () {
  184. Array.prototype.forEach.call(arguments, _remove.bind(this));
  185. }
  186. }
  187. testElement.classList.toggle('c3', false);
  188. // Polyfill for IE 10 and Firefox <24, where classList.toggle does not
  189. // support the second argument.
  190. if (testElement.classList.contains('c3')) {
  191. var _toggle = DOMTokenList.prototype.toggle;
  192. DOMTokenList.prototype.toggle = function (token, force) {
  193. if (1 in arguments && !this.contains(token) === !force) {
  194. return force;
  195. } else {
  196. return _toggle.call(this, token);
  197. }
  198. };
  199. }
  200. testElement = null;
  201. // shallow array comparison
  202. function isEqual (array1, array2) {
  203. return array1.length === array2.length && array1.every(function (element, index) {
  204. return element === array2[index];
  205. });
  206. };
  207. // <editor-fold desc="Shims">
  208. if (!String.prototype.startsWith) {
  209. (function () {
  210. 'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
  211. var defineProperty = (function () {
  212. // IE 8 only supports `Object.defineProperty` on DOM elements
  213. try {
  214. var object = {};
  215. var $defineProperty = Object.defineProperty;
  216. var result = $defineProperty(object, object, object) && $defineProperty;
  217. } catch (error) {
  218. }
  219. return result;
  220. }());
  221. var toString = {}.toString;
  222. var startsWith = function (search) {
  223. if (this == null) {
  224. throw new TypeError();
  225. }
  226. var string = String(this);
  227. if (search && toString.call(search) == '[object RegExp]') {
  228. throw new TypeError();
  229. }
  230. var stringLength = string.length;
  231. var searchString = String(search);
  232. var searchLength = searchString.length;
  233. var position = arguments.length > 1 ? arguments[1] : undefined;
  234. // `ToInteger`
  235. var pos = position ? Number(position) : 0;
  236. if (pos != pos) { // better `isNaN`
  237. pos = 0;
  238. }
  239. var start = Math.min(Math.max(pos, 0), stringLength);
  240. // Avoid the `indexOf` call if no match is possible
  241. if (searchLength + start > stringLength) {
  242. return false;
  243. }
  244. var index = -1;
  245. while (++index < searchLength) {
  246. if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {
  247. return false;
  248. }
  249. }
  250. return true;
  251. };
  252. if (defineProperty) {
  253. defineProperty(String.prototype, 'startsWith', {
  254. 'value': startsWith,
  255. 'configurable': true,
  256. 'writable': true
  257. });
  258. } else {
  259. String.prototype.startsWith = startsWith;
  260. }
  261. }());
  262. }
  263. if (!Object.keys) {
  264. Object.keys = function (
  265. o, // object
  266. k, // key
  267. r // result array
  268. ) {
  269. // initialize object and result
  270. r = [];
  271. // iterate over object keys
  272. for (k in o) {
  273. // fill result array with non-prototypical keys
  274. r.hasOwnProperty.call(o, k) && r.push(k);
  275. }
  276. // return result
  277. return r;
  278. };
  279. }
  280. if (HTMLSelectElement && !HTMLSelectElement.prototype.hasOwnProperty('selectedOptions')) {
  281. Object.defineProperty(HTMLSelectElement.prototype, 'selectedOptions', {
  282. get: function () {
  283. return this.querySelectorAll(':checked');
  284. }
  285. });
  286. }
  287. function getSelectedOptions (select, ignoreDisabled) {
  288. var selectedOptions = select.selectedOptions,
  289. options = [],
  290. opt;
  291. if (ignoreDisabled) {
  292. for (var i = 0, len = selectedOptions.length; i < len; i++) {
  293. opt = selectedOptions[i];
  294. if (!(opt.disabled || opt.parentNode.tagName === 'OPTGROUP' && opt.parentNode.disabled)) {
  295. options.push(opt);
  296. }
  297. }
  298. return options;
  299. }
  300. return selectedOptions;
  301. }
  302. // much faster than $.val()
  303. function getSelectValues (select, selectedOptions) {
  304. var value = [],
  305. options = selectedOptions || select.selectedOptions,
  306. opt;
  307. for (var i = 0, len = options.length; i < len; i++) {
  308. opt = options[i];
  309. if (!(opt.disabled || opt.parentNode.tagName === 'OPTGROUP' && opt.parentNode.disabled)) {
  310. value.push(opt.value || opt.text);
  311. }
  312. }
  313. if (!select.multiple) {
  314. return !value.length ? null : value[0];
  315. }
  316. return value;
  317. }
  318. // set data-selected on select element if the value has been programmatically selected
  319. // prior to initialization of bootstrap-select
  320. // * consider removing or replacing an alternative method *
  321. var valHooks = {
  322. useDefault: false,
  323. _set: $.valHooks.select.set
  324. };
  325. $.valHooks.select.set = function (elem, value) {
  326. if (value && !valHooks.useDefault) $(elem).data('selected', true);
  327. return valHooks._set.apply(this, arguments);
  328. };
  329. var changedArguments = null;
  330. var EventIsSupported = (function () {
  331. try {
  332. new Event('change');
  333. return true;
  334. } catch (e) {
  335. return false;
  336. }
  337. })();
  338. $.fn.triggerNative = function (eventName) {
  339. var el = this[0],
  340. event;
  341. if (el.dispatchEvent) { // for modern browsers & IE9+
  342. if (EventIsSupported) {
  343. // For modern browsers
  344. event = new Event(eventName, {
  345. bubbles: true
  346. });
  347. } else {
  348. // For IE since it doesn't support Event constructor
  349. event = document.createEvent('Event');
  350. event.initEvent(eventName, true, false);
  351. }
  352. el.dispatchEvent(event);
  353. } else if (el.fireEvent) { // for IE8
  354. event = document.createEventObject();
  355. event.eventType = eventName;
  356. el.fireEvent('on' + eventName, event);
  357. } else {
  358. // fall back to jQuery.trigger
  359. this.trigger(eventName);
  360. }
  361. };
  362. // </editor-fold>
  363. function stringSearch (li, searchString, method, normalize) {
  364. var stringTypes = [
  365. 'display',
  366. 'subtext',
  367. 'tokens'
  368. ],
  369. searchSuccess = false;
  370. for (var i = 0; i < stringTypes.length; i++) {
  371. var stringType = stringTypes[i],
  372. string = li[stringType];
  373. if (string) {
  374. string = string.toString();
  375. // Strip HTML tags. This isn't perfect, but it's much faster than any other method
  376. if (stringType === 'display') {
  377. string = string.replace(/<[^>]+>/g, '');
  378. }
  379. if (normalize) string = normalizeToBase(string);
  380. string = string.toUpperCase();
  381. if (method === 'contains') {
  382. searchSuccess = string.indexOf(searchString) >= 0;
  383. } else {
  384. searchSuccess = string.startsWith(searchString);
  385. }
  386. if (searchSuccess) break;
  387. }
  388. }
  389. return searchSuccess;
  390. }
  391. function toInteger (value) {
  392. return parseInt(value, 10) || 0;
  393. }
  394. // Borrowed from Lodash (_.deburr)
  395. /** Used to map Latin Unicode letters to basic Latin letters. */
  396. var deburredLetters = {
  397. // Latin-1 Supplement block.
  398. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  399. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  400. '\xc7': 'C', '\xe7': 'c',
  401. '\xd0': 'D', '\xf0': 'd',
  402. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  403. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  404. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  405. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  406. '\xd1': 'N', '\xf1': 'n',
  407. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  408. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  409. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  410. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  411. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  412. '\xc6': 'Ae', '\xe6': 'ae',
  413. '\xde': 'Th', '\xfe': 'th',
  414. '\xdf': 'ss',
  415. // Latin Extended-A block.
  416. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  417. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  418. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  419. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  420. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  421. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  422. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  423. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  424. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  425. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  426. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  427. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  428. '\u0134': 'J', '\u0135': 'j',
  429. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  430. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  431. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  432. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  433. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  434. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  435. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  436. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  437. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  438. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  439. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  440. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  441. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  442. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  443. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  444. '\u0174': 'W', '\u0175': 'w',
  445. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  446. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  447. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  448. '\u0132': 'IJ', '\u0133': 'ij',
  449. '\u0152': 'Oe', '\u0153': 'oe',
  450. '\u0149': "'n", '\u017f': 's'
  451. };
  452. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  453. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  454. /** Used to compose unicode character classes. */
  455. var rsComboMarksRange = '\\u0300-\\u036f',
  456. reComboHalfMarksRange = '\\ufe20-\\ufe2f',
  457. rsComboSymbolsRange = '\\u20d0-\\u20ff',
  458. rsComboMarksExtendedRange = '\\u1ab0-\\u1aff',
  459. rsComboMarksSupplementRange = '\\u1dc0-\\u1dff',
  460. rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange + rsComboMarksExtendedRange + rsComboMarksSupplementRange;
  461. /** Used to compose unicode capture groups. */
  462. var rsCombo = '[' + rsComboRange + ']';
  463. /**
  464. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  465. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  466. */
  467. var reComboMark = RegExp(rsCombo, 'g');
  468. function deburrLetter (key) {
  469. return deburredLetters[key];
  470. };
  471. function normalizeToBase (string) {
  472. string = string.toString();
  473. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  474. }
  475. // List of HTML entities for escaping.
  476. var escapeMap = {
  477. '&': '&amp;',
  478. '<': '&lt;',
  479. '>': '&gt;',
  480. '"': '&quot;',
  481. "'": '&#x27;',
  482. '`': '&#x60;'
  483. };
  484. // Functions for escaping and unescaping strings to/from HTML interpolation.
  485. var createEscaper = function (map) {
  486. var escaper = function (match) {
  487. return map[match];
  488. };
  489. // Regexes for identifying a key that needs to be escaped.
  490. var source = '(?:' + Object.keys(map).join('|') + ')';
  491. var testRegexp = RegExp(source);
  492. var replaceRegexp = RegExp(source, 'g');
  493. return function (string) {
  494. string = string == null ? '' : '' + string;
  495. return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
  496. };
  497. };
  498. var htmlEscape = createEscaper(escapeMap);
  499. /**
  500. * ------------------------------------------------------------------------
  501. * Constants
  502. * ------------------------------------------------------------------------
  503. */
  504. var keyCodeMap = {
  505. 32: ' ',
  506. 48: '0',
  507. 49: '1',
  508. 50: '2',
  509. 51: '3',
  510. 52: '4',
  511. 53: '5',
  512. 54: '6',
  513. 55: '7',
  514. 56: '8',
  515. 57: '9',
  516. 59: ';',
  517. 65: 'A',
  518. 66: 'B',
  519. 67: 'C',
  520. 68: 'D',
  521. 69: 'E',
  522. 70: 'F',
  523. 71: 'G',
  524. 72: 'H',
  525. 73: 'I',
  526. 74: 'J',
  527. 75: 'K',
  528. 76: 'L',
  529. 77: 'M',
  530. 78: 'N',
  531. 79: 'O',
  532. 80: 'P',
  533. 81: 'Q',
  534. 82: 'R',
  535. 83: 'S',
  536. 84: 'T',
  537. 85: 'U',
  538. 86: 'V',
  539. 87: 'W',
  540. 88: 'X',
  541. 89: 'Y',
  542. 90: 'Z',
  543. 96: '0',
  544. 97: '1',
  545. 98: '2',
  546. 99: '3',
  547. 100: '4',
  548. 101: '5',
  549. 102: '6',
  550. 103: '7',
  551. 104: '8',
  552. 105: '9'
  553. };
  554. var keyCodes = {
  555. ESCAPE: 27, // KeyboardEvent.which value for Escape (Esc) key
  556. ENTER: 13, // KeyboardEvent.which value for Enter key
  557. SPACE: 32, // KeyboardEvent.which value for space key
  558. TAB: 9, // KeyboardEvent.which value for tab key
  559. ARROW_UP: 38, // KeyboardEvent.which value for up arrow key
  560. ARROW_DOWN: 40 // KeyboardEvent.which value for down arrow key
  561. }
  562. var version = {
  563. success: false,
  564. major: '3'
  565. };
  566. try {
  567. version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.');
  568. version.major = version.full[0];
  569. version.success = true;
  570. } catch (err) {
  571. // do nothing
  572. }
  573. var selectId = 0;
  574. var EVENT_KEY = '.bs.select';
  575. var classNames = {
  576. DISABLED: 'disabled',
  577. DIVIDER: 'divider',
  578. SHOW: 'open',
  579. DROPUP: 'dropup',
  580. MENU: 'dropdown-menu',
  581. MENURIGHT: 'dropdown-menu-right',
  582. MENULEFT: 'dropdown-menu-left',
  583. // to-do: replace with more advanced template/customization options
  584. BUTTONCLASS: 'btn-default',
  585. POPOVERHEADER: 'popover-title',
  586. ICONBASE: 'glyphicon',
  587. TICKICON: 'glyphicon-ok'
  588. }
  589. var Selector = {
  590. MENU: '.' + classNames.MENU
  591. }
  592. var elementTemplates = {
  593. span: document.createElement('span'),
  594. i: document.createElement('i'),
  595. subtext: document.createElement('small'),
  596. a: document.createElement('a'),
  597. li: document.createElement('li'),
  598. whitespace: document.createTextNode('\u00A0'),
  599. fragment: document.createDocumentFragment()
  600. }
  601. elementTemplates.a.setAttribute('role', 'option');
  602. elementTemplates.subtext.className = 'text-muted';
  603. elementTemplates.text = elementTemplates.span.cloneNode(false);
  604. elementTemplates.text.className = 'text';
  605. elementTemplates.checkMark = elementTemplates.span.cloneNode(false);
  606. var REGEXP_ARROW = new RegExp(keyCodes.ARROW_UP + '|' + keyCodes.ARROW_DOWN);
  607. var REGEXP_TAB_OR_ESCAPE = new RegExp('^' + keyCodes.TAB + '$|' + keyCodes.ESCAPE);
  608. var generateOption = {
  609. li: function (content, classes, optgroup) {
  610. var li = elementTemplates.li.cloneNode(false);
  611. if (content) {
  612. if (content.nodeType === 1 || content.nodeType === 11) {
  613. li.appendChild(content);
  614. } else {
  615. li.innerHTML = content;
  616. }
  617. }
  618. if (typeof classes !== 'undefined' && classes !== '') li.className = classes;
  619. if (typeof optgroup !== 'undefined' && optgroup !== null) li.classList.add('optgroup-' + optgroup);
  620. return li;
  621. },
  622. a: function (text, classes, inline) {
  623. var a = elementTemplates.a.cloneNode(true);
  624. if (text) {
  625. if (text.nodeType === 11) {
  626. a.appendChild(text);
  627. } else {
  628. a.insertAdjacentHTML('beforeend', text);
  629. }
  630. }
  631. if (typeof classes !== 'undefined' && classes !== '') a.className = classes;
  632. if (version.major === '4') a.classList.add('dropdown-item');
  633. if (inline) a.setAttribute('style', inline);
  634. return a;
  635. },
  636. text: function (options, useFragment) {
  637. var textElement = elementTemplates.text.cloneNode(false),
  638. subtextElement,
  639. iconElement;
  640. if (options.content) {
  641. textElement.innerHTML = options.content;
  642. } else {
  643. textElement.textContent = options.text;
  644. if (options.icon) {
  645. var whitespace = elementTemplates.whitespace.cloneNode(false);
  646. // need to use <i> for icons in the button to prevent a breaking change
  647. // note: switch to span in next major release
  648. iconElement = (useFragment === true ? elementTemplates.i : elementTemplates.span).cloneNode(false);
  649. iconElement.className = options.iconBase + ' ' + options.icon;
  650. elementTemplates.fragment.appendChild(iconElement);
  651. elementTemplates.fragment.appendChild(whitespace);
  652. }
  653. if (options.subtext) {
  654. subtextElement = elementTemplates.subtext.cloneNode(false);
  655. subtextElement.textContent = options.subtext;
  656. textElement.appendChild(subtextElement);
  657. }
  658. }
  659. if (useFragment === true) {
  660. while (textElement.childNodes.length > 0) {
  661. elementTemplates.fragment.appendChild(textElement.childNodes[0]);
  662. }
  663. } else {
  664. elementTemplates.fragment.appendChild(textElement);
  665. }
  666. return elementTemplates.fragment;
  667. },
  668. label: function (options) {
  669. var textElement = elementTemplates.text.cloneNode(false),
  670. subtextElement,
  671. iconElement;
  672. textElement.innerHTML = options.label;
  673. if (options.icon) {
  674. var whitespace = elementTemplates.whitespace.cloneNode(false);
  675. iconElement = elementTemplates.span.cloneNode(false);
  676. iconElement.className = options.iconBase + ' ' + options.icon;
  677. elementTemplates.fragment.appendChild(iconElement);
  678. elementTemplates.fragment.appendChild(whitespace);
  679. }
  680. if (options.subtext) {
  681. subtextElement = elementTemplates.subtext.cloneNode(false);
  682. subtextElement.textContent = options.subtext;
  683. textElement.appendChild(subtextElement);
  684. }
  685. elementTemplates.fragment.appendChild(textElement);
  686. return elementTemplates.fragment;
  687. }
  688. }
  689. var Selectpicker = function (element, options) {
  690. var that = this;
  691. // bootstrap-select has been initialized - revert valHooks.select.set back to its original function
  692. if (!valHooks.useDefault) {
  693. $.valHooks.select.set = valHooks._set;
  694. valHooks.useDefault = true;
  695. }
  696. this.$element = $(element);
  697. this.$newElement = null;
  698. this.$button = null;
  699. this.$menu = null;
  700. this.options = options;
  701. this.selectpicker = {
  702. main: {},
  703. search: {},
  704. current: {}, // current changes if a search is in progress
  705. view: {},
  706. keydown: {
  707. keyHistory: '',
  708. resetKeyHistory: {
  709. start: function () {
  710. return setTimeout(function () {
  711. that.selectpicker.keydown.keyHistory = '';
  712. }, 800);
  713. }
  714. }
  715. }
  716. };
  717. // 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
  718. // data-attribute)
  719. if (this.options.title === null) {
  720. this.options.title = this.$element.attr('title');
  721. }
  722. // Format window padding
  723. var winPad = this.options.windowPadding;
  724. if (typeof winPad === 'number') {
  725. this.options.windowPadding = [winPad, winPad, winPad, winPad];
  726. }
  727. // Expose public methods
  728. this.val = Selectpicker.prototype.val;
  729. this.render = Selectpicker.prototype.render;
  730. this.refresh = Selectpicker.prototype.refresh;
  731. this.setStyle = Selectpicker.prototype.setStyle;
  732. this.selectAll = Selectpicker.prototype.selectAll;
  733. this.deselectAll = Selectpicker.prototype.deselectAll;
  734. this.destroy = Selectpicker.prototype.destroy;
  735. this.remove = Selectpicker.prototype.remove;
  736. this.show = Selectpicker.prototype.show;
  737. this.hide = Selectpicker.prototype.hide;
  738. this.init();
  739. };
  740. Selectpicker.VERSION = '1.13.10';
  741. // part of this is duplicated in i18n/defaults-en_US.js. Make sure to update both.
  742. Selectpicker.DEFAULTS = {
  743. noneSelectedText: 'Nothing selected',
  744. noneResultsText: 'No results matched {0}',
  745. countSelectedText: function (numSelected, numTotal) {
  746. return (numSelected == 1) ? '{0} item selected' : '{0} items selected';
  747. },
  748. maxOptionsText: function (numAll, numGroup) {
  749. return [
  750. (numAll == 1) ? 'Limit reached ({n} item max)' : 'Limit reached ({n} items max)',
  751. (numGroup == 1) ? 'Group limit reached ({n} item max)' : 'Group limit reached ({n} items max)'
  752. ];
  753. },
  754. selectAllText: 'Select All',
  755. deselectAllText: 'Deselect All',
  756. doneButton: false,
  757. doneButtonText: 'Close',
  758. multipleSeparator: ', ',
  759. styleBase: 'btn',
  760. style: classNames.BUTTONCLASS,
  761. size: 'auto',
  762. title: null,
  763. selectedTextFormat: 'values',
  764. width: false,
  765. container: false,
  766. hideDisabled: false,
  767. showSubtext: false,
  768. showIcon: true,
  769. showContent: true,
  770. dropupAuto: true,
  771. header: false,
  772. liveSearch: false,
  773. liveSearchPlaceholder: null,
  774. liveSearchNormalize: false,
  775. liveSearchStyle: 'contains',
  776. actionsBox: false,
  777. iconBase: classNames.ICONBASE,
  778. tickIcon: classNames.TICKICON,
  779. showTick: false,
  780. template: {
  781. caret: '<span class="caret"></span>'
  782. },
  783. maxOptions: false,
  784. mobile: false,
  785. selectOnTab: false,
  786. dropdownAlignRight: false,
  787. windowPadding: 0,
  788. virtualScroll: 600,
  789. display: false,
  790. sanitize: true,
  791. sanitizeFn: null,
  792. whiteList: DefaultWhitelist
  793. };
  794. Selectpicker.prototype = {
  795. constructor: Selectpicker,
  796. init: function () {
  797. var that = this,
  798. id = this.$element.attr('id');
  799. selectId++;
  800. this.selectId = 'bs-select-' + selectId;
  801. this.$element[0].classList.add('bs-select-hidden');
  802. this.multiple = this.$element.prop('multiple');
  803. this.autofocus = this.$element.prop('autofocus');
  804. if (this.$element[0].classList.contains('show-tick')) {
  805. this.options.showTick = true;
  806. }
  807. this.$newElement = this.createDropdown();
  808. this.$element
  809. .after(this.$newElement)
  810. .prependTo(this.$newElement);
  811. this.$button = this.$newElement.children('button');
  812. this.$menu = this.$newElement.children(Selector.MENU);
  813. this.$menuInner = this.$menu.children('.inner');
  814. this.$searchbox = this.$menu.find('input');
  815. this.$element[0].classList.remove('bs-select-hidden');
  816. if (this.options.dropdownAlignRight === true) this.$menu[0].classList.add(classNames.MENURIGHT);
  817. if (typeof id !== 'undefined') {
  818. this.$button.attr('data-id', id);
  819. }
  820. this.checkDisabled();
  821. this.clickListener();
  822. if (this.options.liveSearch) {
  823. this.liveSearchListener();
  824. this.focusedParent = this.$searchbox[0];
  825. } else {
  826. this.focusedParent = this.$menuInner[0];
  827. }
  828. this.setStyle();
  829. this.render();
  830. this.setWidth();
  831. if (this.options.container) {
  832. this.selectPosition();
  833. } else {
  834. this.$element.on('hide' + EVENT_KEY, function () {
  835. if (that.isVirtual()) {
  836. // empty menu on close
  837. var menuInner = that.$menuInner[0],
  838. emptyMenu = menuInner.firstChild.cloneNode(false);
  839. // replace the existing UL with an empty one - this is faster than $.empty() or innerHTML = ''
  840. menuInner.replaceChild(emptyMenu, menuInner.firstChild);
  841. menuInner.scrollTop = 0;
  842. }
  843. });
  844. }
  845. this.$menu.data('this', this);
  846. this.$newElement.data('this', this);
  847. if (this.options.mobile) this.mobile();
  848. this.$newElement.on({
  849. 'hide.bs.dropdown': function (e) {
  850. that.$element.trigger('hide' + EVENT_KEY, e);
  851. },
  852. 'hidden.bs.dropdown': function (e) {
  853. that.$element.trigger('hidden' + EVENT_KEY, e);
  854. },
  855. 'show.bs.dropdown': function (e) {
  856. that.$element.trigger('show' + EVENT_KEY, e);
  857. },
  858. 'shown.bs.dropdown': function (e) {
  859. that.$element.trigger('shown' + EVENT_KEY, e);
  860. }
  861. });
  862. if (that.$element[0].hasAttribute('required')) {
  863. this.$element.on('invalid' + EVENT_KEY, function () {
  864. that.$button[0].classList.add('bs-invalid');
  865. that.$element
  866. .on('shown' + EVENT_KEY + '.invalid', function () {
  867. that.$element
  868. .val(that.$element.val()) // set the value to hide the validation message in Chrome when menu is opened
  869. .off('shown' + EVENT_KEY + '.invalid');
  870. })
  871. .on('rendered' + EVENT_KEY, function () {
  872. // if select is no longer invalid, remove the bs-invalid class
  873. if (this.validity.valid) that.$button[0].classList.remove('bs-invalid');
  874. that.$element.off('rendered' + EVENT_KEY);
  875. });
  876. that.$button.on('blur' + EVENT_KEY, function () {
  877. that.$element.trigger('focus').trigger('blur');
  878. that.$button.off('blur' + EVENT_KEY);
  879. });
  880. });
  881. }
  882. setTimeout(function () {
  883. that.createLi();
  884. that.$element.trigger('loaded' + EVENT_KEY);
  885. });
  886. },
  887. createDropdown: function () {
  888. // Options
  889. // If we are multiple or showTick option is set, then add the show-tick class
  890. var showTick = (this.multiple || this.options.showTick) ? ' show-tick' : '',
  891. multiselectable = this.multiple ? ' aria-multiselectable="true"' : '',
  892. inputGroup = '',
  893. autofocus = this.autofocus ? ' autofocus' : '';
  894. if (version.major < 4 && this.$element.parent().hasClass('input-group')) {
  895. inputGroup = ' input-group-btn';
  896. }
  897. // Elements
  898. var drop,
  899. header = '',
  900. searchbox = '',
  901. actionsbox = '',
  902. donebutton = '';
  903. if (this.options.header) {
  904. header =
  905. '<div class="' + classNames.POPOVERHEADER + '">' +
  906. '<button type="button" class="close" aria-hidden="true">&times;</button>' +
  907. this.options.header +
  908. '</div>';
  909. }
  910. if (this.options.liveSearch) {
  911. searchbox =
  912. '<div class="bs-searchbox">' +
  913. '<input type="text" class="form-control" autocomplete="off"' +
  914. (
  915. this.options.liveSearchPlaceholder === null ? ''
  916. :
  917. ' placeholder="' + htmlEscape(this.options.liveSearchPlaceholder) + '"'
  918. ) +
  919. ' role="combobox" aria-label="Search" aria-controls="' + this.selectId + '" aria-autocomplete="list">' +
  920. '</div>';
  921. }
  922. if (this.multiple && this.options.actionsBox) {
  923. actionsbox =
  924. '<div class="bs-actionsbox">' +
  925. '<div class="btn-group btn-group-sm btn-block">' +
  926. '<button type="button" class="actions-btn bs-select-all btn ' + classNames.BUTTONCLASS + '">' +
  927. this.options.selectAllText +
  928. '</button>' +
  929. '<button type="button" class="actions-btn bs-deselect-all btn ' + classNames.BUTTONCLASS + '">' +
  930. this.options.deselectAllText +
  931. '</button>' +
  932. '</div>' +
  933. '</div>';
  934. }
  935. if (this.multiple && this.options.doneButton) {
  936. donebutton =
  937. '<div class="bs-donebutton">' +
  938. '<div class="btn-group btn-block">' +
  939. '<button type="button" class="btn btn-sm ' + classNames.BUTTONCLASS + '">' +
  940. this.options.doneButtonText +
  941. '</button>' +
  942. '</div>' +
  943. '</div>';
  944. }
  945. drop =
  946. '<div class="dropdown bootstrap-select' + showTick + inputGroup + '">' +
  947. '<button type="button" class="' + this.options.styleBase + ' dropdown-toggle" ' + (this.options.display === 'static' ? 'data-display="static"' : '') + 'data-toggle="dropdown"' + autofocus + ' role="combobox" aria-owns="' + this.selectId + '" aria-haspopup="listbox" aria-expanded="false">' +
  948. '<div class="filter-option">' +
  949. '<div class="filter-option-inner">' +
  950. '<div class="filter-option-inner-inner"></div>' +
  951. '</div> ' +
  952. '</div>' +
  953. (
  954. version.major === '4' ? ''
  955. :
  956. '<span class="bs-caret">' +
  957. this.options.template.caret +
  958. '</span>'
  959. ) +
  960. '</button>' +
  961. '<div class="' + classNames.MENU + ' ' + (version.major === '4' ? '' : classNames.SHOW) + '">' +
  962. header +
  963. searchbox +
  964. actionsbox +
  965. '<div class="inner ' + classNames.SHOW + '" role="listbox" id="' + this.selectId + '" tabindex="-1" ' + multiselectable + '>' +
  966. '<ul class="' + classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : '') + '" role="presentation">' +
  967. '</ul>' +
  968. '</div>' +
  969. donebutton +
  970. '</div>' +
  971. '</div>';
  972. return $(drop);
  973. },
  974. setPositionData: function () {
  975. this.selectpicker.view.canHighlight = [];
  976. this.selectpicker.view.size = 0;
  977. for (var i = 0; i < this.selectpicker.current.data.length; i++) {
  978. var li = this.selectpicker.current.data[i],
  979. canHighlight = true;
  980. if (li.type === 'divider') {
  981. canHighlight = false;
  982. li.height = this.sizeInfo.dividerHeight;
  983. } else if (li.type === 'optgroup-label') {
  984. canHighlight = false;
  985. li.height = this.sizeInfo.dropdownHeaderHeight;
  986. } else {
  987. li.height = this.sizeInfo.liHeight;
  988. }
  989. if (li.disabled) canHighlight = false;
  990. this.selectpicker.view.canHighlight.push(canHighlight);
  991. if (canHighlight) {
  992. this.selectpicker.view.size++;
  993. li.posinset = this.selectpicker.view.size;
  994. }
  995. li.position = (i === 0 ? 0 : this.selectpicker.current.data[i - 1].position) + li.height;
  996. }
  997. },
  998. isVirtual: function () {
  999. return (this.options.virtualScroll !== false) && (this.selectpicker.main.elements.length >= this.options.virtualScroll) || this.options.virtualScroll === true;
  1000. },
  1001. createView: function (isSearching, setSize, refresh) {
  1002. var that = this,
  1003. scrollTop = 0,
  1004. active = [],
  1005. selected,
  1006. prevActive;
  1007. this.selectpicker.current = isSearching ? this.selectpicker.search : this.selectpicker.main;
  1008. this.setPositionData();
  1009. if (setSize) {
  1010. if (refresh) {
  1011. scrollTop = this.$menuInner[0].scrollTop;
  1012. } else if (!that.multiple) {
  1013. var element = that.$element[0],
  1014. selectedIndex = (element.options[element.selectedIndex] || {}).liIndex;
  1015. if (typeof selectedIndex === 'number' && that.options.size !== false) {
  1016. var selectedData = that.selectpicker.main.data[selectedIndex],
  1017. position = selectedData && selectedData.position;
  1018. if (position) {
  1019. scrollTop = position - ((that.sizeInfo.menuInnerHeight + that.sizeInfo.liHeight) / 2);
  1020. }
  1021. }
  1022. }
  1023. }
  1024. scroll(scrollTop, true);
  1025. this.$menuInner.off('scroll.createView').on('scroll.createView', function (e, updateValue) {
  1026. if (!that.noScroll) scroll(this.scrollTop, updateValue);
  1027. that.noScroll = false;
  1028. });
  1029. function scroll (scrollTop, init) {
  1030. var size = that.selectpicker.current.elements.length,
  1031. chunks = [],
  1032. chunkSize,
  1033. chunkCount,
  1034. firstChunk,
  1035. lastChunk,
  1036. currentChunk,
  1037. prevPositions,
  1038. positionIsDifferent,
  1039. previousElements,
  1040. menuIsDifferent = true,
  1041. isVirtual = that.isVirtual();
  1042. that.selectpicker.view.scrollTop = scrollTop;
  1043. if (isVirtual === true) {
  1044. // if an option that is encountered that is wider than the current menu width, update the menu width accordingly
  1045. if (that.sizeInfo.hasScrollBar && that.$menu[0].offsetWidth > that.sizeInfo.totalMenuWidth) {
  1046. that.sizeInfo.menuWidth = that.$menu[0].offsetWidth;
  1047. that.sizeInfo.totalMenuWidth = that.sizeInfo.menuWidth + that.sizeInfo.scrollBarWidth;
  1048. that.$menu.css('min-width', that.sizeInfo.menuWidth);
  1049. }
  1050. }
  1051. chunkSize = Math.ceil(that.sizeInfo.menuInnerHeight / that.sizeInfo.liHeight * 1.5); // number of options in a chunk
  1052. chunkCount = Math.round(size / chunkSize) || 1; // number of chunks
  1053. for (var i = 0; i < chunkCount; i++) {
  1054. var endOfChunk = (i + 1) * chunkSize;
  1055. if (i === chunkCount - 1) {
  1056. endOfChunk = size;
  1057. }
  1058. chunks[i] = [
  1059. (i) * chunkSize + (!i ? 0 : 1),
  1060. endOfChunk
  1061. ];
  1062. if (!size) break;
  1063. if (currentChunk === undefined && scrollTop <= that.selectpicker.current.data[endOfChunk - 1].position - that.sizeInfo.menuInnerHeight) {
  1064. currentChunk = i;
  1065. }
  1066. }
  1067. if (currentChunk === undefined) currentChunk = 0;
  1068. prevPositions = [that.selectpicker.view.position0, that.selectpicker.view.position1];
  1069. // always display previous, current, and next chunks
  1070. firstChunk = Math.max(0, currentChunk - 1);
  1071. lastChunk = Math.min(chunkCount - 1, currentChunk + 1);
  1072. that.selectpicker.view.position0 = isVirtual === false ? 0 : (Math.max(0, chunks[firstChunk][0]) || 0);
  1073. that.selectpicker.view.position1 = isVirtual === false ? size : (Math.min(size, chunks[lastChunk][1]) || 0);
  1074. positionIsDifferent = prevPositions[0] !== that.selectpicker.view.position0 || prevPositions[1] !== that.selectpicker.view.position1;
  1075. if (that.activeIndex !== undefined) {
  1076. prevActive = that.selectpicker.main.elements[that.prevActiveIndex];
  1077. active = that.selectpicker.main.elements[that.activeIndex];
  1078. selected = that.selectpicker.main.elements[that.selectedIndex];
  1079. if (init) {
  1080. if (that.activeIndex !== that.selectedIndex) {
  1081. that.defocusItem(active);
  1082. }
  1083. that.activeIndex = undefined;
  1084. }
  1085. if (that.activeIndex && that.activeIndex !== that.selectedIndex) {
  1086. that.defocusItem(selected);
  1087. }
  1088. }
  1089. if (that.prevActiveIndex !== undefined && that.prevActiveIndex !== that.activeIndex && that.prevActiveIndex !== that.selectedIndex) {
  1090. that.defocusItem(prevActive);
  1091. }
  1092. if (init || positionIsDifferent) {
  1093. previousElements = that.selectpicker.view.visibleElements ? that.selectpicker.view.visibleElements.slice() : [];
  1094. if (isVirtual === false) {
  1095. that.selectpicker.view.visibleElements = that.selectpicker.current.elements;
  1096. } else {
  1097. that.selectpicker.view.visibleElements = that.selectpicker.current.elements.slice(that.selectpicker.view.position0, that.selectpicker.view.position1);
  1098. }
  1099. that.setOptionStatus();
  1100. // if searching, check to make sure the list has actually been updated before updating DOM
  1101. // this prevents unnecessary repaints
  1102. if (isSearching || (isVirtual === false && init)) menuIsDifferent = !isEqual(previousElements, that.selectpicker.view.visibleElements);
  1103. // if virtual scroll is disabled and not searching,
  1104. // menu should never need to be updated more than once
  1105. if ((init || isVirtual === true) && menuIsDifferent) {
  1106. var menuInner = that.$menuInner[0],
  1107. menuFragment = document.createDocumentFragment(),
  1108. emptyMenu = menuInner.firstChild.cloneNode(false),
  1109. marginTop,
  1110. marginBottom,
  1111. elements = that.selectpicker.view.visibleElements,
  1112. toSanitize = [];
  1113. // replace the existing UL with an empty one - this is faster than $.empty()
  1114. menuInner.replaceChild(emptyMenu, menuInner.firstChild);
  1115. for (var i = 0, visibleElementsLen = elements.length; i < visibleElementsLen; i++) {
  1116. var element = elements[i],
  1117. elText,
  1118. elementData;
  1119. if (that.options.sanitize) {
  1120. elText = element.lastChild;
  1121. if (elText) {
  1122. elementData = that.selectpicker.current.data[i + that.selectpicker.view.position0];
  1123. if (elementData && elementData.content && !elementData.sanitized) {
  1124. toSanitize.push(elText);
  1125. elementData.sanitized = true;
  1126. }
  1127. }
  1128. }
  1129. menuFragment.appendChild(element);
  1130. }
  1131. if (that.options.sanitize && toSanitize.length) {
  1132. sanitizeHtml(toSanitize, that.options.whiteList, that.options.sanitizeFn);
  1133. }
  1134. if (isVirtual === true) {
  1135. marginTop = (that.selectpicker.view.position0 === 0 ? 0 : that.selectpicker.current.data[that.selectpicker.view.position0 - 1].position);
  1136. 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);
  1137. menuInner.firstChild.style.marginTop = marginTop + 'px';
  1138. menuInner.firstChild.style.marginBottom = marginBottom + 'px';
  1139. } else {
  1140. menuInner.firstChild.style.marginTop = 0;
  1141. menuInner.firstChild.style.marginBottom = 0;
  1142. }
  1143. menuInner.firstChild.appendChild(menuFragment);
  1144. }
  1145. }
  1146. that.prevActiveIndex = that.activeIndex;
  1147. if (!that.options.liveSearch) {
  1148. that.$menuInner.trigger('focus');
  1149. } else if (isSearching && init) {
  1150. var index = 0,
  1151. newActive;
  1152. if (!that.selectpicker.view.canHighlight[index]) {
  1153. index = 1 + that.selectpicker.view.canHighlight.slice(1).indexOf(true);
  1154. }
  1155. newActive = that.selectpicker.view.visibleElements[index];
  1156. that.defocusItem(that.selectpicker.view.currentActive);
  1157. that.activeIndex = (that.selectpicker.current.data[index] || {}).index;
  1158. that.focusItem(newActive);
  1159. }
  1160. }
  1161. $(window)
  1162. .off('resize' + EVENT_KEY + '.' + this.selectId + '.createView')
  1163. .on('resize' + EVENT_KEY + '.' + this.selectId + '.createView', function () {
  1164. var isActive = that.$newElement.hasClass(classNames.SHOW);
  1165. if (isActive) scroll(that.$menuInner[0].scrollTop);
  1166. });
  1167. },
  1168. focusItem: function (li, liData, noStyle) {
  1169. if (li) {
  1170. liData = liData || this.selectpicker.main.data[this.activeIndex];
  1171. var a = li.firstChild;
  1172. if (a) {
  1173. a.setAttribute('aria-setsize', this.selectpicker.view.size);
  1174. a.setAttribute('aria-posinset', liData.posinset);
  1175. if (noStyle !== true) {
  1176. this.focusedParent.setAttribute('aria-activedescendant', a.id);
  1177. li.classList.add('active');
  1178. a.classList.add('active');
  1179. }
  1180. }
  1181. }
  1182. },
  1183. defocusItem: function (li) {
  1184. if (li) {
  1185. li.classList.remove('active');
  1186. if (li.firstChild) li.firstChild.classList.remove('active');
  1187. }
  1188. },
  1189. setPlaceholder: function () {
  1190. var updateIndex = false;
  1191. if (this.options.title && !this.multiple) {
  1192. if (!this.selectpicker.view.titleOption) this.selectpicker.view.titleOption = document.createElement('option');
  1193. // this option doesn't create a new <li> element, but does add a new option at the start,
  1194. // so startIndex should increase to prevent having to check every option for the bs-title-option class
  1195. updateIndex = true;
  1196. var element = this.$element[0],
  1197. isSelected = false,
  1198. titleNotAppended = !this.selectpicker.view.titleOption.parentNode;
  1199. if (titleNotAppended) {
  1200. // Use native JS to prepend option (faster)
  1201. this.selectpicker.view.titleOption.className = 'bs-title-option';
  1202. this.selectpicker.view.titleOption.value = '';
  1203. // Check if selected or data-selected attribute is already set on an option. If not, select the titleOption option.
  1204. // the selected item may have been changed by user or programmatically before the bootstrap select plugin runs,
  1205. // if so, the select will have the data-selected attribute
  1206. var $opt = $(element.options[element.selectedIndex]);
  1207. isSelected = $opt.attr('selected') === undefined && this.$element.data('selected') === undefined;
  1208. }
  1209. if (titleNotAppended || this.selectpicker.view.titleOption.index !== 0) {
  1210. element.insertBefore(this.selectpicker.view.titleOption, element.firstChild);
  1211. }
  1212. // Set selected *after* appending to select,
  1213. // otherwise the option doesn't get selected in IE
  1214. // set using selectedIndex, as setting the selected attr to true here doesn't work in IE11
  1215. if (isSelected) element.selectedIndex = 0;
  1216. }
  1217. return updateIndex;
  1218. },
  1219. createLi: function () {
  1220. var that = this,
  1221. iconBase = this.options.iconBase,
  1222. optionSelector = ':not([hidden]):not([data-hidden="true"])',
  1223. mainElements = [],
  1224. mainData = [],
  1225. widestOptionLength = 0,
  1226. optID = 0,
  1227. startIndex = this.setPlaceholder() ? 1 : 0; // append the titleOption if necessary and skip the first option in the loop
  1228. if (this.options.hideDisabled) optionSelector += ':not(:disabled)';
  1229. if ((that.options.showTick || that.multiple) && !elementTemplates.checkMark.parentNode) {
  1230. elementTemplates.checkMark.className = iconBase + ' ' + that.options.tickIcon + ' check-mark';
  1231. elementTemplates.a.appendChild(elementTemplates.checkMark);
  1232. }
  1233. var selectOptions = this.$element[0].querySelectorAll('select > *' + optionSelector);
  1234. function addDivider (config) {
  1235. var previousData = mainData[mainData.length - 1];
  1236. // ensure optgroup doesn't create back-to-back dividers
  1237. if (
  1238. previousData &&
  1239. previousData.type === 'divider' &&
  1240. (previousData.optID || config.optID)
  1241. ) {
  1242. return;
  1243. }
  1244. config = config || {};
  1245. config.type = 'divider';
  1246. mainElements.push(
  1247. generateOption.li(
  1248. false,
  1249. classNames.DIVIDER,
  1250. (config.optID ? config.optID + 'div' : undefined)
  1251. )
  1252. );
  1253. mainData.push(config);
  1254. }
  1255. function addOption (option, config) {
  1256. config = config || {};
  1257. config.divider = option.getAttribute('data-divider') === 'true';
  1258. if (config.divider) {
  1259. addDivider({
  1260. optID: config.optID
  1261. });
  1262. } else {
  1263. var liIndex = mainData.length,
  1264. cssText = option.style.cssText,
  1265. inlineStyle = cssText ? htmlEscape(cssText) : '',
  1266. optionClass = (option.className || '') + (config.optgroupClass || '');
  1267. if (config.optID) optionClass = 'opt ' + optionClass;
  1268. config.text = option.textContent;
  1269. config.content = option.getAttribute('data-content');
  1270. config.tokens = option.getAttribute('data-tokens');
  1271. config.subtext = option.getAttribute('data-subtext');
  1272. config.icon = option.getAttribute('data-icon');
  1273. config.iconBase = iconBase;
  1274. var textElement = generateOption.text(config);
  1275. var liElement = generateOption.li(
  1276. generateOption.a(
  1277. textElement,
  1278. optionClass,
  1279. inlineStyle
  1280. ),
  1281. '',
  1282. config.optID
  1283. );
  1284. if (liElement.firstChild) {
  1285. liElement.firstChild.id = that.selectId + '-' + liIndex;
  1286. }
  1287. mainElements.push(liElement);
  1288. option.liIndex = liIndex;
  1289. config.display = config.content || config.text;
  1290. config.type = 'option';
  1291. config.index = liIndex;
  1292. config.option = option;
  1293. config.disabled = config.disabled || option.disabled;
  1294. mainData.push(config);
  1295. var combinedLength = 0;
  1296. // count the number of characters in the option - not perfect, but should work in most cases
  1297. if (config.display) combinedLength += config.display.length;
  1298. if (config.subtext) combinedLength += config.subtext.length;
  1299. // if there is an icon, ensure this option's width is checked
  1300. if (config.icon) combinedLength += 1;
  1301. if (combinedLength > widestOptionLength) {
  1302. widestOptionLength = combinedLength;
  1303. // guess which option is the widest
  1304. // use this when calculating menu width
  1305. // not perfect, but it's fast, and the width will be updating accordingly when scrolling
  1306. that.selectpicker.view.widestOption = mainElements[mainElements.length - 1];
  1307. }
  1308. }
  1309. }
  1310. function addOptgroup (index, selectOptions) {
  1311. var optgroup = selectOptions[index],
  1312. previous = selectOptions[index - 1],
  1313. next = selectOptions[index + 1],
  1314. options = optgroup.querySelectorAll('option' + optionSelector);
  1315. if (!options.length) return;
  1316. var config = {
  1317. label: htmlEscape(optgroup.label),
  1318. subtext: optgroup.getAttribute('data-subtext'),
  1319. icon: optgroup.getAttribute('data-icon'),
  1320. iconBase: iconBase
  1321. },
  1322. optgroupClass = ' ' + (optgroup.className || ''),
  1323. headerIndex,
  1324. lastIndex;
  1325. optID++;
  1326. if (previous) {
  1327. addDivider({ optID: optID });
  1328. }
  1329. var labelElement = generateOption.label(config);
  1330. mainElements.push(
  1331. generateOption.li(labelElement, 'dropdown-header' + optgroupClass, optID)
  1332. );
  1333. mainData.push({
  1334. display: config.label,
  1335. subtext: config.subtext,
  1336. type: 'optgroup-label',
  1337. optID: optID
  1338. });
  1339. for (var j = 0, len = options.length; j < len; j++) {
  1340. var option = options[j];
  1341. if (j === 0) {
  1342. headerIndex = mainData.length - 1;
  1343. lastIndex = headerIndex + len;
  1344. }
  1345. addOption(option, {
  1346. headerIndex: headerIndex,
  1347. lastIndex: lastIndex,
  1348. optID: optID,
  1349. optgroupClass: optgroupClass,
  1350. disabled: optgroup.disabled
  1351. });
  1352. }
  1353. if (next) {
  1354. addDivider({ optID: optID });
  1355. }
  1356. }
  1357. for (var len = selectOptions.length; startIndex < len; startIndex++) {
  1358. var item = selectOptions[startIndex];
  1359. if (item.tagName !== 'OPTGROUP') {
  1360. addOption(item, {});
  1361. } else {
  1362. addOptgroup(startIndex, selectOptions);
  1363. }
  1364. }
  1365. this.selectpicker.main.elements = mainElements;
  1366. this.selectpicker.main.data = mainData;
  1367. this.selectpicker.current = this.selectpicker.main;
  1368. },
  1369. findLis: function () {
  1370. return this.$menuInner.find('.inner > li');
  1371. },
  1372. render: function () {
  1373. // ensure titleOption is appended and selected (if necessary) before getting selectedOptions
  1374. this.setPlaceholder();
  1375. var that = this,
  1376. element = this.$element[0],
  1377. selectedOptions = getSelectedOptions(element, this.options.hideDisabled),
  1378. selectedCount = selectedOptions.length,
  1379. button = this.$button[0],
  1380. buttonInner = button.querySelector('.filter-option-inner-inner'),
  1381. multipleSeparator = document.createTextNode(this.options.multipleSeparator),
  1382. titleFragment = elementTemplates.fragment.cloneNode(false),
  1383. showCount,
  1384. countMax,
  1385. hasContent = false;
  1386. button.classList.toggle('bs-placeholder', that.multiple ? !selectedCount : !getSelectValues(element, selectedOptions));
  1387. this.tabIndex();
  1388. if (this.options.selectedTextFormat === 'static') {
  1389. titleFragment = generateOption.text({ text: this.options.title }, true);
  1390. } else {
  1391. showCount = this.multiple && this.options.selectedTextFormat.indexOf('count') !== -1 && selectedCount > 1;
  1392. // determine if the number of selected options will be shown (showCount === true)
  1393. if (showCount) {
  1394. countMax = this.options.selectedTextFormat.split('>');
  1395. showCount = (countMax.length > 1 && selectedCount > countMax[1]) || (countMax.length === 1 && selectedCount >= 2);
  1396. }
  1397. // only loop through all selected options if the count won't be shown
  1398. if (showCount === false) {
  1399. for (var selectedIndex = 0; selectedIndex < selectedCount; selectedIndex++) {
  1400. if (selectedIndex < 50) {
  1401. var option = selectedOptions[selectedIndex],
  1402. titleOptions = {},
  1403. thisData = {
  1404. content: option.getAttribute('data-content'),
  1405. subtext: option.getAttribute('data-subtext'),
  1406. icon: option.getAttribute('data-icon')
  1407. };
  1408. if (this.multiple && selectedIndex > 0) {
  1409. titleFragment.appendChild(multipleSeparator.cloneNode(false));
  1410. }
  1411. if (option.title) {
  1412. titleOptions.text = option.title;
  1413. } else if (thisData.content && that.options.showContent) {
  1414. titleOptions.content = thisData.content.toString();
  1415. hasContent = true;
  1416. } else {
  1417. if (that.options.showIcon) {
  1418. titleOptions.icon = thisData.icon;
  1419. titleOptions.iconBase = this.options.iconBase;
  1420. }
  1421. if (that.options.showSubtext && !that.multiple && thisData.subtext) titleOptions.subtext = ' ' + thisData.subtext;
  1422. titleOptions.text = option.textContent.trim();
  1423. }
  1424. titleFragment.appendChild(generateOption.text(titleOptions, true));
  1425. } else {
  1426. break;
  1427. }
  1428. }
  1429. // add ellipsis
  1430. if (selectedCount > 49) {
  1431. titleFragment.appendChild(document.createTextNode('...'));
  1432. }
  1433. } else {
  1434. var optionSelector = ':not([hidden]):not([data-hidden="true"]):not([data-divider="true"])';
  1435. if (this.options.hideDisabled) optionSelector += ':not(:disabled)';
  1436. // If this is a multiselect, and selectedTextFormat is count, then show 1 of 2 selected, etc.
  1437. var totalCount = this.$element[0].querySelectorAll('select > option' + optionSelector + ', optgroup' + optionSelector + ' option' + optionSelector).length,
  1438. tr8nText = (typeof this.options.countSelectedText === 'function') ? this.options.countSelectedText(selectedCount, totalCount) : this.options.countSelectedText;
  1439. titleFragment = generateOption.text({
  1440. text: tr8nText.replace('{0}', selectedCount.toString()).replace('{1}', totalCount.toString())
  1441. }, true);
  1442. }
  1443. }
  1444. if (this.options.title == undefined) {
  1445. // use .attr to ensure undefined is returned if title attribute is not set
  1446. this.options.title = this.$element.attr('title');
  1447. }
  1448. // If the select doesn't have a title, then use the default, or if nothing is set at all, use noneSelectedText
  1449. if (!titleFragment.childNodes.length) {
  1450. titleFragment = generateOption.text({
  1451. text: typeof this.options.title !== 'undefined' ? this.options.title : this.options.noneSelectedText
  1452. }, true);
  1453. }
  1454. // strip all HTML tags and trim the result, then unescape any escaped tags
  1455. button.title = titleFragment.textContent.replace(/<[^>]*>?/g, '').trim();
  1456. if (this.options.sanitize && hasContent) {
  1457. sanitizeHtml([titleFragment], that.options.whiteList, that.options.sanitizeFn);
  1458. }
  1459. buttonInner.innerHTML = '';
  1460. buttonInner.appendChild(titleFragment);
  1461. if (version.major < 4 && this.$newElement[0].classList.contains('bs3-has-addon')) {
  1462. var filterExpand = button.querySelector('.filter-expand'),
  1463. clone = buttonInner.cloneNode(true);
  1464. clone.className = 'filter-expand';
  1465. if (filterExpand) {
  1466. button.replaceChild(clone, filterExpand);
  1467. } else {
  1468. button.appendChild(clone);
  1469. }
  1470. }
  1471. this.$element.trigger('rendered' + EVENT_KEY);
  1472. },
  1473. /**
  1474. * @param [style]
  1475. * @param [status]
  1476. */
  1477. setStyle: function (newStyle, status) {
  1478. var button = this.$button[0],
  1479. newElement = this.$newElement[0],
  1480. style = this.options.style.trim(),
  1481. buttonClass;
  1482. if (this.$element.attr('class')) {
  1483. this.$newElement.addClass(this.$element.attr('class').replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi, ''));
  1484. }
  1485. if (version.major < 4) {
  1486. newElement.classList.add('bs3');
  1487. if (newElement.parentNode.classList.contains('input-group') &&
  1488. (newElement.previousElementSibling || newElement.nextElementSibling) &&
  1489. (newElement.previousElementSibling || newElement.nextElementSibling).classList.contains('input-group-addon')
  1490. ) {
  1491. newElement.classList.add('bs3-has-addon');
  1492. }
  1493. }
  1494. if (newStyle) {
  1495. buttonClass = newStyle.trim();
  1496. } else {
  1497. buttonClass = style;
  1498. }
  1499. if (status == 'add') {
  1500. if (buttonClass) button.classList.add.apply(button.classList, buttonClass.split(' '));
  1501. } else if (status == 'remove') {
  1502. if (buttonClass) button.classList.remove.apply(button.classList, buttonClass.split(' '));
  1503. } else {
  1504. if (style) button.classList.remove.apply(button.classList, style.split(' '));
  1505. if (buttonClass) button.classList.add.apply(button.classList, buttonClass.split(' '));
  1506. }
  1507. },
  1508. liHeight: function (refresh) {
  1509. if (!refresh && (this.options.size === false || this.sizeInfo)) return;
  1510. if (!this.sizeInfo) this.sizeInfo = {};
  1511. var newElement = document.createElement('div'),
  1512. menu = document.createElement('div'),
  1513. menuInner = document.createElement('div'),
  1514. menuInnerInner = document.createElement('ul'),
  1515. divider = document.createElement('li'),
  1516. dropdownHeader = document.createElement('li'),
  1517. li = document.createElement('li'),
  1518. a = document.createElement('a'),
  1519. text = document.createElement('span'),
  1520. header = this.options.header && this.$menu.find('.' + classNames.POPOVERHEADER).length > 0 ? this.$menu.find('.' + classNames.POPOVERHEADER)[0].cloneNode(true) : null,
  1521. search = this.options.liveSearch ? document.createElement('div') : null,
  1522. actions = this.options.actionsBox && this.multiple && this.$menu.find('.bs-actionsbox').length > 0 ? this.$menu.find('.bs-actionsbox')[0].cloneNode(true) : null,
  1523. doneButton = this.options.doneButton && this.multiple && this.$menu.find('.bs-donebutton').length > 0 ? this.$menu.find('.bs-donebutton')[0].cloneNode(true) : null,
  1524. firstOption = this.$element.find('option')[0];
  1525. this.sizeInfo.selectWidth = this.$newElement[0].offsetWidth;
  1526. text.className = 'text';
  1527. a.className = 'dropdown-item ' + (firstOption ? firstOption.className : '');
  1528. newElement.className = this.$menu[0].parentNode.className + ' ' + classNames.SHOW;
  1529. newElement.style.width = this.sizeInfo.selectWidth + 'px';
  1530. if (this.options.width === 'auto') menu.style.minWidth = 0;
  1531. menu.className = classNames.MENU + ' ' + classNames.SHOW;
  1532. menuInner.className = 'inner ' + classNames.SHOW;
  1533. menuInnerInner.className = classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : '');
  1534. divider.className = classNames.DIVIDER;
  1535. dropdownHeader.className = 'dropdown-header';
  1536. text.appendChild(document.createTextNode('\u200b'));
  1537. a.appendChild(text);
  1538. li.appendChild(a);
  1539. dropdownHeader.appendChild(text.cloneNode(true));
  1540. if (this.selectpicker.view.widestOption) {
  1541. menuInnerInner.appendChild(this.selectpicker.view.widestOption.cloneNode(true));
  1542. }
  1543. menuInnerInner.appendChild(li);
  1544. menuInnerInner.appendChild(divider);
  1545. menuInnerInner.appendChild(dropdownHeader);
  1546. if (header) menu.appendChild(header);
  1547. if (search) {
  1548. var input = document.createElement('input');
  1549. search.className = 'bs-searchbox';
  1550. input.className = 'form-control';
  1551. search.appendChild(input);
  1552. menu.appendChild(search);
  1553. }
  1554. if (actions) menu.appendChild(actions);
  1555. menuInner.appendChild(menuInnerInner);
  1556. menu.appendChild(menuInner);
  1557. if (doneButton) menu.appendChild(doneButton);
  1558. newElement.appendChild(menu);
  1559. document.body.appendChild(newElement);
  1560. var liHeight = li.offsetHeight,
  1561. dropdownHeaderHeight = dropdownHeader ? dropdownHeader.offsetHeight : 0,
  1562. headerHeight = header ? header.offsetHeight : 0,
  1563. searchHeight = search ? search.offsetHeight : 0,
  1564. actionsHeight = actions ? actions.offsetHeight : 0,
  1565. doneButtonHeight = doneButton ? doneButton.offsetHeight : 0,
  1566. dividerHeight = $(divider).outerHeight(true),
  1567. // fall back to jQuery if getComputedStyle is not supported
  1568. menuStyle = window.getComputedStyle ? window.getComputedStyle(menu) : false,
  1569. menuWidth = menu.offsetWidth,
  1570. $menu = menuStyle ? null : $(menu),
  1571. menuPadding = {
  1572. vert: toInteger(menuStyle ? menuStyle.paddingTop : $menu.css('paddingTop')) +
  1573. toInteger(menuStyle ? menuStyle.paddingBottom : $menu.css('paddingBottom')) +
  1574. toInteger(menuStyle ? menuStyle.borderTopWidth : $menu.css('borderTopWidth')) +
  1575. toInteger(menuStyle ? menuStyle.borderBottomWidth : $menu.css('borderBottomWidth')),
  1576. horiz: toInteger(menuStyle ? menuStyle.paddingLeft : $menu.css('paddingLeft')) +
  1577. toInteger(menuStyle ? menuStyle.paddingRight : $menu.css('paddingRight')) +
  1578. toInteger(menuStyle ? menuStyle.borderLeftWidth : $menu.css('borderLeftWidth')) +
  1579. toInteger(menuStyle ? menuStyle.borderRightWidth : $menu.css('borderRightWidth'))
  1580. },
  1581. menuExtras = {
  1582. vert: menuPadding.vert +
  1583. toInteger(menuStyle ? menuStyle.marginTop : $menu.css('marginTop')) +
  1584. toInteger(menuStyle ? menuStyle.marginBottom : $menu.css('marginBottom')) + 2,
  1585. horiz: menuPadding.horiz +
  1586. toInteger(menuStyle ? menuStyle.marginLeft : $menu.css('marginLeft')) +
  1587. toInteger(menuStyle ? menuStyle.marginRight : $menu.css('marginRight')) + 2
  1588. },
  1589. scrollBarWidth;
  1590. menuInner.style.overflowY = 'scroll';
  1591. scrollBarWidth = menu.offsetWidth - menuWidth;
  1592. document.body.removeChild(newElement);
  1593. this.sizeInfo.liHeight = liHeight;
  1594. this.sizeInfo.dropdownHeaderHeight = dropdownHeaderHeight;
  1595. this.sizeInfo.headerHeight = headerHeight;
  1596. this.sizeInfo.searchHeight = searchHeight;
  1597. this.sizeInfo.actionsHeight = actionsHeight;
  1598. this.sizeInfo.doneButtonHeight = doneButtonHeight;
  1599. this.sizeInfo.dividerHeight = dividerHeight;
  1600. this.sizeInfo.menuPadding = menuPadding;
  1601. this.sizeInfo.menuExtras = menuExtras;
  1602. this.sizeInfo.menuWidth = menuWidth;
  1603. this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth;
  1604. this.sizeInfo.scrollBarWidth = scrollBarWidth;
  1605. this.sizeInfo.selectHeight = this.$newElement[0].offsetHeight;
  1606. this.setPositionData();
  1607. },
  1608. getSelectPosition: function () {
  1609. var that = this,
  1610. $window = $(window),
  1611. pos = that.$newElement.offset(),
  1612. $container = $(that.options.container),
  1613. containerPos;
  1614. if (that.options.container && $container.length && !$container.is('body')) {
  1615. containerPos = $container.offset();
  1616. containerPos.top += parseInt($container.css('borderTopWidth'));
  1617. containerPos.left += parseInt($container.css('borderLeftWidth'));
  1618. } else {
  1619. containerPos = { top: 0, left: 0 };
  1620. }
  1621. var winPad = that.options.windowPadding;
  1622. this.sizeInfo.selectOffsetTop = pos.top - containerPos.top - $window.scrollTop();
  1623. this.sizeInfo.selectOffsetBot = $window.height() - this.sizeInfo.selectOffsetTop - this.sizeInfo.selectHeight - containerPos.top - winPad[2];
  1624. this.sizeInfo.selectOffsetLeft = pos.left - containerPos.left - $window.scrollLeft();
  1625. this.sizeInfo.selectOffsetRight = $window.width() - this.sizeInfo.selectOffsetLeft - this.sizeInfo.selectWidth - containerPos.left - winPad[1];
  1626. this.sizeInfo.selectOffsetTop -= winPad[0];
  1627. this.sizeInfo.selectOffsetLeft -= winPad[3];
  1628. },
  1629. setMenuSize: function (isAuto) {
  1630. this.getSelectPosition();
  1631. var selectWidth = this.sizeInfo.selectWidth,
  1632. liHeight = this.sizeInfo.liHeight,
  1633. headerHeight = this.sizeInfo.headerHeight,
  1634. searchHeight = this.sizeInfo.searchHeight,
  1635. actionsHeight = this.sizeInfo.actionsHeight,
  1636. doneButtonHeight = this.sizeInfo.doneButtonHeight,
  1637. divHeight = this.sizeInfo.dividerHeight,
  1638. menuPadding = this.sizeInfo.menuPadding,
  1639. menuInnerHeight,
  1640. menuHeight,
  1641. divLength = 0,
  1642. minHeight,
  1643. _minHeight,
  1644. maxHeight,
  1645. menuInnerMinHeight,
  1646. estimate;
  1647. if (this.options.dropupAuto) {
  1648. // Get the estimated height of the menu without scrollbars.
  1649. // This is useful for smaller menus, where there might be plenty of room
  1650. // below the button without setting dropup, but we can't know
  1651. // the exact height of the menu until createView is called later
  1652. estimate = liHeight * this.selectpicker.current.elements.length + menuPadding.vert;
  1653. this.$newElement.toggleClass(classNames.DROPUP, this.sizeInfo.selectOffsetTop - this.sizeInfo.selectOffsetBot > this.sizeInfo.menuExtras.vert && estimate + this.sizeInfo.menuExtras.vert + 50 > this.sizeInfo.selectOffsetBot);
  1654. }
  1655. if (this.options.size === 'auto') {
  1656. _minHeight = this.selectpicker.current.elements.length > 3 ? this.sizeInfo.liHeight * 3 + this.sizeInfo.menuExtras.vert - 2 : 0;
  1657. menuHeight = this.sizeInfo.selectOffsetBot - this.sizeInfo.menuExtras.vert;
  1658. minHeight = _minHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
  1659. menuInnerMinHeight = Math.max(_minHeight - menuPadding.vert, 0);
  1660. if (this.$newElement.hasClass(classNames.DROPUP)) {
  1661. menuHeight = this.sizeInfo.selectOffsetTop - this.sizeInfo.menuExtras.vert;
  1662. }
  1663. maxHeight = menuHeight;
  1664. menuInnerHeight = menuHeight - headerHeight - searchHeight - actionsHeight - doneButtonHeight - menuPadding.vert;
  1665. } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
  1666. for (var i = 0; i < this.options.size; i++) {
  1667. if (this.selectpicker.current.data[i].type === 'divider') divLength++;
  1668. }
  1669. menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding.vert;
  1670. menuInnerHeight = menuHeight - menuPadding.vert;
  1671. maxHeight = menuHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
  1672. minHeight = menuInnerMinHeight = '';
  1673. }
  1674. if (this.options.dropdownAlignRight === 'auto') {
  1675. this.$menu.toggleClass(classNames.MENURIGHT, this.sizeInfo.selectOffsetLeft > this.sizeInfo.selectOffsetRight && this.sizeInfo.selectOffsetRight < (this.sizeInfo.totalMenuWidth - selectWidth));
  1676. }
  1677. this.$menu.css({
  1678. 'max-height': maxHeight + 'px',
  1679. 'overflow': 'hidden',
  1680. 'min-height': minHeight + 'px'
  1681. });
  1682. this.$menuInner.css({
  1683. 'max-height': menuInnerHeight + 'px',
  1684. 'overflow-y': 'auto',
  1685. 'min-height': menuInnerMinHeight + 'px'
  1686. });
  1687. // ensure menuInnerHeight is always a positive number to prevent issues calculating chunkSize in createView
  1688. this.sizeInfo.menuInnerHeight = Math.max(menuInnerHeight, 1);
  1689. if (this.selectpicker.current.data.length && this.selectpicker.current.data[this.selectpicker.current.data.length - 1].position > this.sizeInfo.menuInnerHeight) {
  1690. this.sizeInfo.hasScrollBar = true;
  1691. this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth + this.sizeInfo.scrollBarWidth;
  1692. this.$menu.css('min-width', this.sizeInfo.totalMenuWidth);
  1693. }
  1694. if (this.dropdown && this.dropdown._popper) this.dropdown._popper.update();
  1695. },
  1696. setSize: function (refresh) {
  1697. this.liHeight(refresh);
  1698. if (this.options.header) this.$menu.css('padding-top', 0);
  1699. if (this.options.size === false) return;
  1700. var that = this,
  1701. $window = $(window);
  1702. this.setMenuSize();
  1703. if (this.options.liveSearch) {
  1704. this.$searchbox
  1705. .off('input.setMenuSize propertychange.setMenuSize')
  1706. .on('input.setMenuSize propertychange.setMenuSize', function () {
  1707. return that.setMenuSize();
  1708. });
  1709. }
  1710. if (this.options.size === 'auto') {
  1711. $window
  1712. .off('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize')
  1713. .on('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize', function () {
  1714. return that.setMenuSize();
  1715. });
  1716. } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
  1717. $window.off('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize');
  1718. }
  1719. that.createView(false, true, refresh);
  1720. },
  1721. setWidth: function () {
  1722. var that = this;
  1723. if (this.options.width === 'auto') {
  1724. requestAnimationFrame(function () {
  1725. that.$menu.css('min-width', '0');
  1726. that.$element.on('loaded' + EVENT_KEY, function () {
  1727. that.liHeight();
  1728. that.setMenuSize();
  1729. // Get correct width if element is hidden
  1730. var $selectClone = that.$newElement.clone().appendTo('body'),
  1731. btnWidth = $selectClone.css('width', 'auto').children('button').outerWidth();
  1732. $selectClone.remove();
  1733. // Set width to whatever's larger, button title or longest option
  1734. that.sizeInfo.selectWidth = Math.max(that.sizeInfo.totalMenuWidth, btnWidth);
  1735. that.$newElement.css('width', that.sizeInfo.selectWidth + 'px');
  1736. });
  1737. });
  1738. } else if (this.options.width === 'fit') {
  1739. // Remove inline min-width so width can be changed from 'auto'
  1740. this.$menu.css('min-width', '');
  1741. this.$newElement.css('width', '').addClass('fit-width');
  1742. } else if (this.options.width) {
  1743. // Remove inline min-width so width can be changed from 'auto'
  1744. this.$menu.css('min-width', '');
  1745. this.$newElement.css('width', this.options.width);
  1746. } else {
  1747. // Remove inline min-width/width so width can be changed
  1748. this.$menu.css('min-width', '');
  1749. this.$newElement.css('width', '');
  1750. }
  1751. // Remove fit-width class if width is changed programmatically
  1752. if (this.$newElement.hasClass('fit-width') && this.options.width !== 'fit') {
  1753. this.$newElement[0].classList.remove('fit-width');
  1754. }
  1755. },
  1756. selectPosition: function () {
  1757. this.$bsContainer = $('<div class="bs-container" />');
  1758. var that = this,
  1759. $container = $(this.options.container),
  1760. pos,
  1761. containerPos,
  1762. actualHeight,
  1763. getPlacement = function ($element) {
  1764. var containerPosition = {},
  1765. // fall back to dropdown's default display setting if display is not manually set
  1766. display = that.options.display || (
  1767. // Bootstrap 3 doesn't have $.fn.dropdown.Constructor.Default
  1768. $.fn.dropdown.Constructor.Default ? $.fn.dropdown.Constructor.Default.display
  1769. : false
  1770. );
  1771. that.$bsContainer.addClass($element.attr('class').replace(/form-control|fit-width/gi, '')).toggleClass(classNames.DROPUP, $element.hasClass(classNames.DROPUP));
  1772. pos = $element.offset();
  1773. if (!$container.is('body')) {
  1774. containerPos = $container.offset();
  1775. containerPos.top += parseInt($container.css('borderTopWidth')) - $container.scrollTop();
  1776. containerPos.left += parseInt($container.css('borderLeftWidth')) - $container.scrollLeft();
  1777. } else {
  1778. containerPos = { top: 0, left: 0 };
  1779. }
  1780. actualHeight = $element.hasClass(classNames.DROPUP) ? 0 : $element[0].offsetHeight;
  1781. // Bootstrap 4+ uses Popper for menu positioning
  1782. if (version.major < 4 || display === 'static') {
  1783. containerPosition.top = pos.top - containerPos.top + actualHeight;
  1784. containerPosition.left = pos.left - containerPos.left;
  1785. }
  1786. containerPosition.width = $element[0].offsetWidth;
  1787. that.$bsContainer.css(containerPosition);
  1788. };
  1789. this.$button.on('click.bs.dropdown.data-api', function () {
  1790. if (that.isDisabled()) {
  1791. return;
  1792. }
  1793. getPlacement(that.$newElement);
  1794. that.$bsContainer
  1795. .appendTo(that.options.container)
  1796. .toggleClass(classNames.SHOW, !that.$button.hasClass(classNames.SHOW))
  1797. .append(that.$menu);
  1798. });
  1799. $(window)
  1800. .off('resize' + EVENT_KEY + '.' + this.selectId + ' scroll' + EVENT_KEY + '.' + this.selectId)
  1801. .on('resize' + EVENT_KEY + '.' + this.selectId + ' scroll' + EVENT_KEY + '.' + this.selectId, function () {
  1802. var isActive = that.$newElement.hasClass(classNames.SHOW);
  1803. if (isActive) getPlacement(that.$newElement);
  1804. });
  1805. this.$element.on('hide' + EVENT_KEY, function () {
  1806. that.$menu.data('height', that.$menu.height());
  1807. that.$bsContainer.detach();
  1808. });
  1809. },
  1810. setOptionStatus: function (selectedOnly) {
  1811. var that = this;
  1812. that.noScroll = false;
  1813. if (that.selectpicker.view.visibleElements && that.selectpicker.view.visibleElements.length) {
  1814. for (var i = 0; i < that.selectpicker.view.visibleElements.length; i++) {
  1815. var liData = that.selectpicker.current.data[i + that.selectpicker.view.position0],
  1816. option = liData.option;
  1817. if (option) {
  1818. if (selectedOnly !== true) {
  1819. that.setDisabled(
  1820. liData.index,
  1821. liData.disabled
  1822. );
  1823. }
  1824. that.setSelected(
  1825. liData.index,
  1826. option.selected
  1827. );
  1828. }
  1829. }
  1830. }
  1831. },
  1832. /**
  1833. * @param {number} index - the index of the option that is being changed
  1834. * @param {boolean} selected - true if the option is being selected, false if being deselected
  1835. */
  1836. setSelected: function (index, selected) {
  1837. var li = this.selectpicker.main.elements[index],
  1838. liData = this.selectpicker.main.data[index],
  1839. activeIndexIsSet = this.activeIndex !== undefined,
  1840. thisIsActive = this.activeIndex === index,
  1841. prevActive,
  1842. a,
  1843. // if current option is already active
  1844. // OR
  1845. // if the current option is being selected, it's NOT multiple, and
  1846. // activeIndex is undefined:
  1847. // - when the menu is first being opened, OR
  1848. // - after a search has been performed, OR
  1849. // - 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)
  1850. keepActive = thisIsActive || (selected && !this.multiple && !activeIndexIsSet);
  1851. liData.selected = selected;
  1852. a = li.firstChild;
  1853. if (selected) {
  1854. this.selectedIndex = index;
  1855. }
  1856. li.classList.toggle('selected', selected);
  1857. if (keepActive) {
  1858. this.focusItem(li, liData);
  1859. this.selectpicker.view.currentActive = li;
  1860. this.activeIndex = index;
  1861. } else {
  1862. this.defocusItem(li);
  1863. }
  1864. if (a) {
  1865. a.classList.toggle('selected', selected);
  1866. if (selected) {
  1867. a.setAttribute('aria-selected', true);
  1868. } else {
  1869. if (this.multiple) {
  1870. a.setAttribute('aria-selected', false);
  1871. } else {
  1872. a.removeAttribute('aria-selected');
  1873. }
  1874. }
  1875. }
  1876. if (!keepActive && !activeIndexIsSet && selected && this.prevActiveIndex !== undefined) {
  1877. prevActive = this.selectpicker.main.elements[this.prevActiveIndex];
  1878. this.defocusItem(prevActive);
  1879. }
  1880. },
  1881. /**
  1882. * @param {number} index - the index of the option that is being disabled
  1883. * @param {boolean} disabled - true if the option is being disabled, false if being enabled
  1884. */
  1885. setDisabled: function (index, disabled) {
  1886. var li = this.selectpicker.main.elements[index],
  1887. a;
  1888. this.selectpicker.main.data[index].disabled = disabled;
  1889. a = li.firstChild;
  1890. li.classList.toggle(classNames.DISABLED, disabled);
  1891. if (a) {
  1892. if (version.major === '4') a.classList.toggle(classNames.DISABLED, disabled);
  1893. if (disabled) {
  1894. a.setAttribute('aria-disabled', disabled);
  1895. a.setAttribute('tabindex', -1);
  1896. } else {
  1897. a.removeAttribute('aria-disabled');
  1898. a.setAttribute('tabindex', 0);
  1899. }
  1900. }
  1901. },
  1902. isDisabled: function () {
  1903. return this.$element[0].disabled;
  1904. },
  1905. checkDisabled: function () {
  1906. var that = this;
  1907. if (this.isDisabled()) {
  1908. this.$newElement[0].classList.add(classNames.DISABLED);
  1909. this.$button.addClass(classNames.DISABLED).attr('tabindex', -1).attr('aria-disabled', true);
  1910. } else {
  1911. if (this.$button[0].classList.contains(classNames.DISABLED)) {
  1912. this.$newElement[0].classList.remove(classNames.DISABLED);
  1913. this.$button.removeClass(classNames.DISABLED).attr('aria-disabled', false);
  1914. }
  1915. if (this.$button.attr('tabindex') == -1 && !this.$element.data('tabindex')) {
  1916. this.$button.removeAttr('tabindex');
  1917. }
  1918. }
  1919. this.$button.on('click', function () {
  1920. return !that.isDisabled();
  1921. });
  1922. },
  1923. tabIndex: function () {
  1924. if (this.$element.data('tabindex') !== this.$element.attr('tabindex') &&
  1925. (this.$element.attr('tabindex') !== -98 && this.$element.attr('tabindex') !== '-98')) {
  1926. this.$element.data('tabindex', this.$element.attr('tabindex'));
  1927. this.$button.attr('tabindex', this.$element.data('tabindex'));
  1928. }
  1929. this.$element.attr('tabindex', -98);
  1930. },
  1931. clickListener: function () {
  1932. var that = this,
  1933. $document = $(document);
  1934. $document.data('spaceSelect', false);
  1935. this.$button.on('keyup', function (e) {
  1936. if (/(32)/.test(e.keyCode.toString(10)) && $document.data('spaceSelect')) {
  1937. e.preventDefault();
  1938. $document.data('spaceSelect', false);
  1939. }
  1940. });
  1941. this.$newElement.on('show.bs.dropdown', function () {
  1942. if (version.major > 3 && !that.dropdown) {
  1943. that.dropdown = that.$button.data('bs.dropdown');
  1944. that.dropdown._menu = that.$menu[0];
  1945. }
  1946. });
  1947. this.$button.on('click.bs.dropdown.data-api', function () {
  1948. if (!that.$newElement.hasClass(classNames.SHOW)) {
  1949. that.setSize();
  1950. }
  1951. });
  1952. function setFocus () {
  1953. if (that.options.liveSearch) {
  1954. that.$searchbox.trigger('focus');
  1955. } else {
  1956. that.$menuInner.trigger('focus');
  1957. }
  1958. }
  1959. function checkPopperExists () {
  1960. if (that.dropdown && that.dropdown._popper && that.dropdown._popper.state.isCreated) {
  1961. setFocus();
  1962. } else {
  1963. requestAnimationFrame(checkPopperExists);
  1964. }
  1965. }
  1966. this.$element.on('shown' + EVENT_KEY, function () {
  1967. if (that.$menuInner[0].scrollTop !== that.selectpicker.view.scrollTop) {
  1968. that.$menuInner[0].scrollTop = that.selectpicker.view.scrollTop;
  1969. }
  1970. if (version.major > 3) {
  1971. requestAnimationFrame(checkPopperExists);
  1972. } else {
  1973. setFocus();
  1974. }
  1975. });
  1976. // ensure posinset and setsize are correct before selecting an option via a click
  1977. this.$menuInner.on('mouseenter', 'li a', function (e) {
  1978. var hoverLi = this.parentElement,
  1979. position0 = that.isVirtual() ? that.selectpicker.view.position0 : 0,
  1980. index = Array.prototype.indexOf.call(hoverLi.parentElement.children, hoverLi),
  1981. hoverData = that.selectpicker.current.data[index + position0];
  1982. that.focusItem(hoverLi, hoverData, true);
  1983. });
  1984. this.$menuInner.on('click', 'li a', function (e, retainActive) {
  1985. var $this = $(this),
  1986. element = that.$element[0],
  1987. position0 = that.isVirtual() ? that.selectpicker.view.position0 : 0,
  1988. clickedData = that.selectpicker.current.data[$this.parent().index() + position0],
  1989. clickedIndex = clickedData.index,
  1990. prevValue = getSelectValues(element),
  1991. prevIndex = element.selectedIndex,
  1992. prevOption = element.options[prevIndex],
  1993. triggerChange = true;
  1994. // Don't close on multi choice menu
  1995. if (that.multiple && that.options.maxOptions !== 1) {
  1996. e.stopPropagation();
  1997. }
  1998. e.preventDefault();
  1999. // Don't run if the select is disabled
  2000. if (!that.isDisabled() && !$this.parent().hasClass(classNames.DISABLED)) {
  2001. var $options = that.$element.find('option'),
  2002. option = clickedData.option,
  2003. $option = $(option),
  2004. state = option.selected,
  2005. $optgroup = $option.parent('optgroup'),
  2006. $optgroupOptions = $optgroup.find('option'),
  2007. maxOptions = that.options.maxOptions,
  2008. maxOptionsGrp = $optgroup.data('maxOptions') || false;
  2009. if (clickedIndex === that.activeIndex) retainActive = true;
  2010. if (!retainActive) {
  2011. that.prevActiveIndex = that.activeIndex;
  2012. that.activeIndex = undefined;
  2013. }
  2014. if (!that.multiple) { // Deselect all others if not multi select box
  2015. prevOption.selected = false;
  2016. option.selected = true;
  2017. that.setSelected(clickedIndex, true);
  2018. } else { // Toggle the one we have chosen if we are multi select.
  2019. option.selected = !state;
  2020. that.setSelected(clickedIndex, !state);
  2021. $this.trigger('blur');
  2022. if (maxOptions !== false || maxOptionsGrp !== false) {
  2023. var maxReached = maxOptions < $options.filter(':selected').length,
  2024. maxReachedGrp = maxOptionsGrp < $optgroup.find('option:selected').length;
  2025. if ((maxOptions && maxReached) || (maxOptionsGrp && maxReachedGrp)) {
  2026. if (maxOptions && maxOptions == 1) {
  2027. $options.prop('selected', false);
  2028. $option.prop('selected', true);
  2029. for (var i = 0; i < $options.length; i++) {
  2030. that.setSelected(i, false);
  2031. }
  2032. that.setSelected(clickedIndex, true);
  2033. } else if (maxOptionsGrp && maxOptionsGrp == 1) {
  2034. $optgroup.find('option:selected').prop('selected', false);
  2035. $option.prop('selected', true);
  2036. for (var i = 0; i < $optgroupOptions.length; i++) {
  2037. var option = $optgroupOptions[i];
  2038. that.setSelected($options.index(option), false);
  2039. }
  2040. that.setSelected(clickedIndex, true);
  2041. } else {
  2042. var maxOptionsText = typeof that.options.maxOptionsText === 'string' ? [that.options.maxOptionsText, that.options.maxOptionsText] : that.options.maxOptionsText,
  2043. maxOptionsArr = typeof maxOptionsText === 'function' ? maxOptionsText(maxOptions, maxOptionsGrp) : maxOptionsText,
  2044. maxTxt = maxOptionsArr[0].replace('{n}', maxOptions),
  2045. maxTxtGrp = maxOptionsArr[1].replace('{n}', maxOptionsGrp),
  2046. $notify = $('<div class="notify"></div>');
  2047. // If {var} is set in array, replace it
  2048. /** @deprecated */
  2049. if (maxOptionsArr[2]) {
  2050. maxTxt = maxTxt.replace('{var}', maxOptionsArr[2][maxOptions > 1 ? 0 : 1]);
  2051. maxTxtGrp = maxTxtGrp.replace('{var}', maxOptionsArr[2][maxOptionsGrp > 1 ? 0 : 1]);
  2052. }
  2053. $option.prop('selected', false);
  2054. that.$menu.append($notify);
  2055. if (maxOptions && maxReached) {
  2056. $notify.append($('<div>' + maxTxt + '</div>'));
  2057. triggerChange = false;
  2058. that.$element.trigger('maxReached' + EVENT_KEY);
  2059. }
  2060. if (maxOptionsGrp && maxReachedGrp) {
  2061. $notify.append($('<div>' + maxTxtGrp + '</div>'));
  2062. triggerChange = false;
  2063. that.$element.trigger('maxReachedGrp' + EVENT_KEY);
  2064. }
  2065. setTimeout(function () {
  2066. that.setSelected(clickedIndex, false);
  2067. }, 10);
  2068. $notify.delay(750).fadeOut(300, function () {
  2069. $(this).remove();
  2070. });
  2071. }
  2072. }
  2073. }
  2074. }
  2075. if (!that.multiple || (that.multiple && that.options.maxOptions === 1)) {
  2076. that.$button.trigger('focus');
  2077. } else if (that.options.liveSearch) {
  2078. that.$searchbox.trigger('focus');
  2079. }
  2080. // Trigger select 'change'
  2081. if (triggerChange) {
  2082. if (that.multiple || prevIndex !== element.selectedIndex) {
  2083. // $option.prop('selected') is current option state (selected/unselected). prevValue is the value of the select prior to being changed.
  2084. changedArguments = [option.index, $option.prop('selected'), prevValue];
  2085. that.$element
  2086. .triggerNative('change');
  2087. }
  2088. }
  2089. }
  2090. });
  2091. this.$menu.on('click', 'li.' + classNames.DISABLED + ' a, .' + classNames.POPOVERHEADER + ', .' + classNames.POPOVERHEADER + ' :not(.close)', function (e) {
  2092. if (e.currentTarget == this) {
  2093. e.preventDefault();
  2094. e.stopPropagation();
  2095. if (that.options.liveSearch && !$(e.target).hasClass('close')) {
  2096. that.$searchbox.trigger('focus');
  2097. } else {
  2098. that.$button.trigger('focus');
  2099. }
  2100. }
  2101. });
  2102. this.$menuInner.on('click', '.divider, .dropdown-header', function (e) {
  2103. e.preventDefault();
  2104. e.stopPropagation();
  2105. if (that.options.liveSearch) {
  2106. that.$searchbox.trigger('focus');
  2107. } else {
  2108. that.$button.trigger('focus');
  2109. }
  2110. });
  2111. this.$menu.on('click', '.' + classNames.POPOVERHEADER + ' .close', function () {
  2112. that.$button.trigger('click');
  2113. });
  2114. this.$searchbox.on('click', function (e) {
  2115. e.stopPropagation();
  2116. });
  2117. this.$menu.on('click', '.actions-btn', function (e) {
  2118. if (that.options.liveSearch) {
  2119. that.$searchbox.trigger('focus');
  2120. } else {
  2121. that.$button.trigger('focus');
  2122. }
  2123. e.preventDefault();
  2124. e.stopPropagation();
  2125. if ($(this).hasClass('bs-select-all')) {
  2126. that.selectAll();
  2127. } else {
  2128. that.deselectAll();
  2129. }
  2130. });
  2131. this.$element
  2132. .on('change' + EVENT_KEY, function () {
  2133. that.render();
  2134. that.$element.trigger('changed' + EVENT_KEY, changedArguments);
  2135. changedArguments = null;
  2136. })
  2137. .on('focus' + EVENT_KEY, function () {
  2138. if (!that.options.mobile) that.$button.trigger('focus');
  2139. });
  2140. },
  2141. liveSearchListener: function () {
  2142. var that = this,
  2143. noResults = document.createElement('li');
  2144. this.$button.on('click.bs.dropdown.data-api', function () {
  2145. if (!!that.$searchbox.val()) {
  2146. that.$searchbox.val('');
  2147. }
  2148. });
  2149. this.$searchbox.on('click.bs.dropdown.data-api focus.bs.dropdown.data-api touchend.bs.dropdown.data-api', function (e) {
  2150. e.stopPropagation();
  2151. });
  2152. this.$searchbox.on('input propertychange', function () {
  2153. var searchValue = that.$searchbox.val();
  2154. that.selectpicker.search.elements = [];
  2155. that.selectpicker.search.data = [];
  2156. if (searchValue) {
  2157. var i,
  2158. searchMatch = [],
  2159. q = searchValue.toUpperCase(),
  2160. cache = {},
  2161. cacheArr = [],
  2162. searchStyle = that._searchStyle(),
  2163. normalizeSearch = that.options.liveSearchNormalize;
  2164. if (normalizeSearch) q = normalizeToBase(q);
  2165. that._$lisSelected = that.$menuInner.find('.selected');
  2166. for (var i = 0; i < that.selectpicker.main.data.length; i++) {
  2167. var li = that.selectpicker.main.data[i];
  2168. if (!cache[i]) {
  2169. cache[i] = stringSearch(li, q, searchStyle, normalizeSearch);
  2170. }
  2171. if (cache[i] && li.headerIndex !== undefined && cacheArr.indexOf(li.headerIndex) === -1) {
  2172. if (li.headerIndex > 0) {
  2173. cache[li.headerIndex - 1] = true;
  2174. cacheArr.push(li.headerIndex - 1);
  2175. }
  2176. cache[li.headerIndex] = true;
  2177. cacheArr.push(li.headerIndex);
  2178. cache[li.lastIndex + 1] = true;
  2179. }
  2180. if (cache[i] && li.type !== 'optgroup-label') cacheArr.push(i);
  2181. }
  2182. for (var i = 0, cacheLen = cacheArr.length; i < cacheLen; i++) {
  2183. var index = cacheArr[i],
  2184. prevIndex = cacheArr[i - 1],
  2185. li = that.selectpicker.main.data[index],
  2186. liPrev = that.selectpicker.main.data[prevIndex];
  2187. if (li.type !== 'divider' || (li.type === 'divider' && liPrev && liPrev.type !== 'divider' && cacheLen - 1 !== i)) {
  2188. that.selectpicker.search.data.push(li);
  2189. searchMatch.push(that.selectpicker.main.elements[index]);
  2190. }
  2191. }
  2192. that.activeIndex = undefined;
  2193. that.noScroll = true;
  2194. that.$menuInner.scrollTop(0);
  2195. that.selectpicker.search.elements = searchMatch;
  2196. that.createView(true);
  2197. if (!searchMatch.length) {
  2198. noResults.className = 'no-results';
  2199. noResults.innerHTML = that.options.noneResultsText.replace('{0}', '"' + htmlEscape(searchValue) + '"');
  2200. that.$menuInner[0].firstChild.appendChild(noResults);
  2201. }
  2202. } else {
  2203. that.$menuInner.scrollTop(0);
  2204. that.createView(false);
  2205. }
  2206. });
  2207. },
  2208. _searchStyle: function () {
  2209. return this.options.liveSearchStyle || 'contains';
  2210. },
  2211. val: function (value) {
  2212. var element = this.$element[0];
  2213. if (typeof value !== 'undefined') {
  2214. var prevValue = getSelectValues(element);
  2215. changedArguments = [null, null, prevValue];
  2216. this.$element
  2217. .val(value)
  2218. .trigger('changed' + EVENT_KEY, changedArguments);
  2219. if (this.$newElement.hasClass(classNames.SHOW)) {
  2220. if (this.multiple) {
  2221. this.setOptionStatus(true);
  2222. } else {
  2223. var liSelectedIndex = (element.options[element.selectedIndex] || {}).liIndex;
  2224. if (typeof liSelectedIndex === 'number') {
  2225. this.setSelected(this.selectedIndex, false);
  2226. this.setSelected(liSelectedIndex, true);
  2227. }
  2228. }
  2229. }
  2230. this.render();
  2231. changedArguments = null;
  2232. return this.$element;
  2233. } else {
  2234. return this.$element.val();
  2235. }
  2236. },
  2237. changeAll: function (status) {
  2238. if (!this.multiple) return;
  2239. if (typeof status === 'undefined') status = true;
  2240. var element = this.$element[0],
  2241. previousSelected = 0,
  2242. currentSelected = 0,
  2243. prevValue = getSelectValues(element);
  2244. element.classList.add('bs-select-hidden');
  2245. for (var i = 0, len = this.selectpicker.current.elements.length; i < len; i++) {
  2246. var liData = this.selectpicker.current.data[i],
  2247. option = liData.option;
  2248. if (option && !liData.disabled && liData.type !== 'divider') {
  2249. if (liData.selected) previousSelected++;
  2250. option.selected = status;
  2251. if (status) currentSelected++;
  2252. }
  2253. }
  2254. element.classList.remove('bs-select-hidden');
  2255. if (previousSelected === currentSelected) return;
  2256. this.setOptionStatus();
  2257. changedArguments = [null, null, prevValue];
  2258. this.$element
  2259. .triggerNative('change');
  2260. },
  2261. selectAll: function () {
  2262. return this.changeAll(true);
  2263. },
  2264. deselectAll: function () {
  2265. return this.changeAll(false);
  2266. },
  2267. toggle: function (e) {
  2268. e = e || window.event;
  2269. if (e) e.stopPropagation();
  2270. this.$button.trigger('click.bs.dropdown.data-api');
  2271. },
  2272. keydown: function (e) {
  2273. var $this = $(this),
  2274. isToggle = $this.hasClass('dropdown-toggle'),
  2275. $parent = isToggle ? $this.closest('.dropdown') : $this.closest(Selector.MENU),
  2276. that = $parent.data('this'),
  2277. $items = that.findLis(),
  2278. index,
  2279. isActive,
  2280. liActive,
  2281. activeLi,
  2282. offset,
  2283. updateScroll = false,
  2284. downOnTab = e.which === keyCodes.TAB && !isToggle && !that.options.selectOnTab,
  2285. isArrowKey = REGEXP_ARROW.test(e.which) || downOnTab,
  2286. scrollTop = that.$menuInner[0].scrollTop,
  2287. isVirtual = that.isVirtual(),
  2288. position0 = isVirtual === true ? that.selectpicker.view.position0 : 0;
  2289. isActive = that.$newElement.hasClass(classNames.SHOW);
  2290. if (
  2291. !isActive &&
  2292. (
  2293. isArrowKey ||
  2294. (e.which >= 48 && e.which <= 57) ||
  2295. (e.which >= 96 && e.which <= 105) ||
  2296. (e.which >= 65 && e.which <= 90)
  2297. )
  2298. ) {
  2299. that.$button.trigger('click.bs.dropdown.data-api');
  2300. if (that.options.liveSearch) {
  2301. that.$searchbox.trigger('focus');
  2302. return;
  2303. }
  2304. }
  2305. if (e.which === keyCodes.ESCAPE && isActive) {
  2306. e.preventDefault();
  2307. that.$button.trigger('click.bs.dropdown.data-api').trigger('focus');
  2308. }
  2309. if (isArrowKey) { // if up or down
  2310. if (!$items.length) return;
  2311. liActive = that.selectpicker.main.elements[that.activeIndex];
  2312. index = liActive ? Array.prototype.indexOf.call(liActive.parentElement.children, liActive) : -1;
  2313. if (index !== -1) {
  2314. that.defocusItem(liActive);
  2315. }
  2316. if (e.which === keyCodes.ARROW_UP) { // up
  2317. if (index !== -1) index--;
  2318. if (index + position0 < 0) index += $items.length;
  2319. if (!that.selectpicker.view.canHighlight[index + position0]) {
  2320. index = that.selectpicker.view.canHighlight.slice(0, index + position0).lastIndexOf(true) - position0;
  2321. if (index === -1) index = $items.length - 1;
  2322. }
  2323. } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down
  2324. index++;
  2325. if (index + position0 >= that.selectpicker.view.canHighlight.length) index = 0;
  2326. if (!that.selectpicker.view.canHighlight[index + position0]) {
  2327. index = index + 1 + that.selectpicker.view.canHighlight.slice(index + position0 + 1).indexOf(true);
  2328. }
  2329. }
  2330. e.preventDefault();
  2331. var liActiveIndex = position0 + index;
  2332. if (e.which === keyCodes.ARROW_UP) { // up
  2333. // scroll to bottom and highlight last option
  2334. if (position0 === 0 && index === $items.length - 1) {
  2335. that.$menuInner[0].scrollTop = that.$menuInner[0].scrollHeight;
  2336. liActiveIndex = that.selectpicker.current.elements.length - 1;
  2337. } else {
  2338. activeLi = that.selectpicker.current.data[liActiveIndex];
  2339. offset = activeLi.position - activeLi.height;
  2340. updateScroll = offset < scrollTop;
  2341. }
  2342. } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down
  2343. // scroll to top and highlight first option
  2344. if (index === 0) {
  2345. that.$menuInner[0].scrollTop = 0;
  2346. liActiveIndex = 0;
  2347. } else {
  2348. activeLi = that.selectpicker.current.data[liActiveIndex];
  2349. offset = activeLi.position - that.sizeInfo.menuInnerHeight;
  2350. updateScroll = offset > scrollTop;
  2351. }
  2352. }
  2353. liActive = that.selectpicker.current.elements[liActiveIndex];
  2354. that.activeIndex = that.selectpicker.current.data[liActiveIndex].index;
  2355. that.focusItem(liActive);
  2356. that.selectpicker.view.currentActive = liActive;
  2357. if (updateScroll) that.$menuInner[0].scrollTop = offset;
  2358. if (that.options.liveSearch) {
  2359. that.$searchbox.trigger('focus');
  2360. } else {
  2361. $this.trigger('focus');
  2362. }
  2363. } else if (
  2364. (!$this.is('input') && !REGEXP_TAB_OR_ESCAPE.test(e.which)) ||
  2365. (e.which === keyCodes.SPACE && that.selectpicker.keydown.keyHistory)
  2366. ) {
  2367. var searchMatch,
  2368. matches = [],
  2369. keyHistory;
  2370. e.preventDefault();
  2371. that.selectpicker.keydown.keyHistory += keyCodeMap[e.which];
  2372. if (that.selectpicker.keydown.resetKeyHistory.cancel) clearTimeout(that.selectpicker.keydown.resetKeyHistory.cancel);
  2373. that.selectpicker.keydown.resetKeyHistory.cancel = that.selectpicker.keydown.resetKeyHistory.start();
  2374. keyHistory = that.selectpicker.keydown.keyHistory;
  2375. // if all letters are the same, set keyHistory to just the first character when searching
  2376. if (/^(.)\1+$/.test(keyHistory)) {
  2377. keyHistory = keyHistory.charAt(0);
  2378. }
  2379. // find matches
  2380. for (var i = 0; i < that.selectpicker.current.data.length; i++) {
  2381. var li = that.selectpicker.current.data[i],
  2382. hasMatch;
  2383. hasMatch = stringSearch(li, keyHistory, 'startsWith', true);
  2384. if (hasMatch && that.selectpicker.view.canHighlight[i]) {
  2385. matches.push(li.index);
  2386. }
  2387. }
  2388. if (matches.length) {
  2389. var matchIndex = 0;
  2390. $items.removeClass('active').find('a').removeClass('active');
  2391. // either only one key has been pressed or they are all the same key
  2392. if (keyHistory.length === 1) {
  2393. matchIndex = matches.indexOf(that.activeIndex);
  2394. if (matchIndex === -1 || matchIndex === matches.length - 1) {
  2395. matchIndex = 0;
  2396. } else {
  2397. matchIndex++;
  2398. }
  2399. }
  2400. searchMatch = matches[matchIndex];
  2401. activeLi = that.selectpicker.main.data[searchMatch];
  2402. if (scrollTop - activeLi.position > 0) {
  2403. offset = activeLi.position - activeLi.height;
  2404. updateScroll = true;
  2405. } else {
  2406. offset = activeLi.position - that.sizeInfo.menuInnerHeight;
  2407. // if the option is already visible at the current scroll position, just keep it the same
  2408. updateScroll = activeLi.position > scrollTop + that.sizeInfo.menuInnerHeight;
  2409. }
  2410. liActive = that.selectpicker.main.elements[searchMatch];
  2411. that.activeIndex = matches[matchIndex];
  2412. that.focusItem(liActive);
  2413. if (liActive) liActive.firstChild.focus();
  2414. if (updateScroll) that.$menuInner[0].scrollTop = offset;
  2415. $this.trigger('focus');
  2416. }
  2417. }
  2418. // Select focused option if "Enter", "Spacebar" or "Tab" (when selectOnTab is true) are pressed inside the menu.
  2419. if (
  2420. isActive &&
  2421. (
  2422. (e.which === keyCodes.SPACE && !that.selectpicker.keydown.keyHistory) ||
  2423. e.which === keyCodes.ENTER ||
  2424. (e.which === keyCodes.TAB && that.options.selectOnTab)
  2425. )
  2426. ) {
  2427. if (e.which !== keyCodes.SPACE) e.preventDefault();
  2428. if (!that.options.liveSearch || e.which !== keyCodes.SPACE) {
  2429. that.$menuInner.find('.active a').trigger('click', true); // retain active class
  2430. $this.trigger('focus');
  2431. if (!that.options.liveSearch) {
  2432. // Prevent screen from scrolling if the user hits the spacebar
  2433. e.preventDefault();
  2434. // Fixes spacebar selection of dropdown items in FF & IE
  2435. $(document).data('spaceSelect', true);
  2436. }
  2437. }
  2438. }
  2439. },
  2440. mobile: function () {
  2441. this.$element[0].classList.add('mobile-device');
  2442. },
  2443. refresh: function () {
  2444. // update options if data attributes have been changed
  2445. var config = $.extend({}, this.options, this.$element.data());
  2446. this.options = config;
  2447. this.checkDisabled();
  2448. this.setStyle();
  2449. this.render();
  2450. this.createLi();
  2451. this.setWidth();
  2452. this.setSize(true);
  2453. this.$element.trigger('refreshed' + EVENT_KEY);
  2454. },
  2455. hide: function () {
  2456. this.$newElement.hide();
  2457. },
  2458. show: function () {
  2459. this.$newElement.show();
  2460. },
  2461. remove: function () {
  2462. this.$newElement.remove();
  2463. this.$element.remove();
  2464. },
  2465. destroy: function () {
  2466. this.$newElement.before(this.$element).remove();
  2467. if (this.$bsContainer) {
  2468. this.$bsContainer.remove();
  2469. } else {
  2470. this.$menu.remove();
  2471. }
  2472. this.$element
  2473. .off(EVENT_KEY)
  2474. .removeData('selectpicker')
  2475. .removeClass('bs-select-hidden selectpicker');
  2476. $(window).off(EVENT_KEY + '.' + this.selectId);
  2477. }
  2478. };
  2479. // SELECTPICKER PLUGIN DEFINITION
  2480. // ==============================
  2481. function Plugin (option) {
  2482. // get the args of the outer function..
  2483. var args = arguments;
  2484. // The arguments of the function are explicitly re-defined from the argument list, because the shift causes them
  2485. // to get lost/corrupted in android 2.3 and IE9 #715 #775
  2486. var _option = option;
  2487. [].shift.apply(args);
  2488. // if the version was not set successfully
  2489. if (!version.success) {
  2490. // try to retreive it again
  2491. try {
  2492. version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.');
  2493. } catch (err) {
  2494. // fall back to use BootstrapVersion if set
  2495. if (Selectpicker.BootstrapVersion) {
  2496. version.full = Selectpicker.BootstrapVersion.split(' ')[0].split('.');
  2497. } else {
  2498. version.full = [version.major, '0', '0'];
  2499. console.warn(
  2500. 'There was an issue retrieving Bootstrap\'s version. ' +
  2501. 'Ensure Bootstrap is being loaded before bootstrap-select and there is no namespace collision. ' +
  2502. 'If loading Bootstrap asynchronously, the version may need to be manually specified via $.fn.selectpicker.Constructor.BootstrapVersion.',
  2503. err
  2504. );
  2505. }
  2506. }
  2507. version.major = version.full[0];
  2508. version.success = true;
  2509. }
  2510. if (version.major === '4') {
  2511. // some defaults need to be changed if using Bootstrap 4
  2512. // check to see if they have already been manually changed before forcing them to update
  2513. var toUpdate = [];
  2514. if (Selectpicker.DEFAULTS.style === classNames.BUTTONCLASS) toUpdate.push({ name: 'style', className: 'BUTTONCLASS' });
  2515. if (Selectpicker.DEFAULTS.iconBase === classNames.ICONBASE) toUpdate.push({ name: 'iconBase', className: 'ICONBASE' });
  2516. if (Selectpicker.DEFAULTS.tickIcon === classNames.TICKICON) toUpdate.push({ name: 'tickIcon', className: 'TICKICON' });
  2517. classNames.DIVIDER = 'dropdown-divider';
  2518. classNames.SHOW = 'show';
  2519. classNames.BUTTONCLASS = 'btn-light';
  2520. classNames.POPOVERHEADER = 'popover-header';
  2521. classNames.ICONBASE = '';
  2522. classNames.TICKICON = 'bs-ok-default';
  2523. for (var i = 0; i < toUpdate.length; i++) {
  2524. var option = toUpdate[i];
  2525. Selectpicker.DEFAULTS[option.name] = classNames[option.className];
  2526. }
  2527. }
  2528. var value;
  2529. var chain = this.each(function () {
  2530. var $this = $(this);
  2531. if ($this.is('select')) {
  2532. var data = $this.data('selectpicker'),
  2533. options = typeof _option == 'object' && _option;
  2534. if (!data) {
  2535. var dataAttributes = $this.data();
  2536. for (var dataAttr in dataAttributes) {
  2537. if (dataAttributes.hasOwnProperty(dataAttr) && $.inArray(dataAttr, DISALLOWED_ATTRIBUTES) !== -1) {
  2538. delete dataAttributes[dataAttr];
  2539. }
  2540. }
  2541. var config = $.extend({}, Selectpicker.DEFAULTS, $.fn.selectpicker.defaults || {}, dataAttributes, options);
  2542. config.template = $.extend({}, Selectpicker.DEFAULTS.template, ($.fn.selectpicker.defaults ? $.fn.selectpicker.defaults.template : {}), dataAttributes.template, options.template);
  2543. $this.data('selectpicker', (data = new Selectpicker(this, config)));
  2544. } else if (options) {
  2545. for (var i in options) {
  2546. if (options.hasOwnProperty(i)) {
  2547. data.options[i] = options[i];
  2548. }
  2549. }
  2550. }
  2551. if (typeof _option == 'string') {
  2552. if (data[_option] instanceof Function) {
  2553. value = data[_option].apply(data, args);
  2554. } else {
  2555. value = data.options[_option];
  2556. }
  2557. }
  2558. }
  2559. });
  2560. if (typeof value !== 'undefined') {
  2561. // noinspection JSUnusedAssignment
  2562. return value;
  2563. } else {
  2564. return chain;
  2565. }
  2566. }
  2567. var old = $.fn.selectpicker;
  2568. $.fn.selectpicker = Plugin;
  2569. $.fn.selectpicker.Constructor = Selectpicker;
  2570. // SELECTPICKER NO CONFLICT
  2571. // ========================
  2572. $.fn.selectpicker.noConflict = function () {
  2573. $.fn.selectpicker = old;
  2574. return this;
  2575. };
  2576. $(document)
  2577. .off('keydown.bs.dropdown.data-api')
  2578. .on('keydown' + EVENT_KEY, '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input', Selectpicker.prototype.keydown)
  2579. .on('focusin.modal', '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input', function (e) {
  2580. e.stopPropagation();
  2581. });
  2582. // SELECTPICKER DATA-API
  2583. // =====================
  2584. $(window).on('load' + EVENT_KEY + '.data-api', function () {
  2585. $('.selectpicker').each(function () {
  2586. var $selectpicker = $(this);
  2587. Plugin.call($selectpicker, $selectpicker.data());
  2588. })
  2589. });
  2590. })(jQuery);
  2591. }));
  2592. //# sourceMappingURL=bootstrap-select.js.map