004-bootstrap-select.js 110 KB

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