004-bootstrap-select.js 123 KB

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