bootstrap-select.js 113 KB

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