bootstrap-select.js 101 KB

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