bootstrap-select.js 96 KB

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