bootstrap-select.js 102 KB

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