Bez popisu

bootstrap-select.js 108KB

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