003-bootstrap-select.js 125 KB

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