bootstrap-select.js 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737
  1. /*!
  2. * Bootstrap-select v1.13.2 (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.2';
  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': 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');
  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 header = this.options.header ? '<div class="' + classNames.POPOVERHEADER + '"><button type="button" class="close" aria-hidden="true">&times;</button>' + this.options.header + '</div>' : '';
  585. var searchbox = this.options.liveSearch ?
  586. '<div class="bs-searchbox">' +
  587. '<input type="text" class="form-control" autocomplete="off"' +
  588. (null === this.options.liveSearchPlaceholder ? '' : ' placeholder="' + htmlEscape(this.options.liveSearchPlaceholder) + '"') + ' role="textbox" aria-label="Search">' +
  589. '</div>'
  590. : '';
  591. var actionsbox = this.multiple && this.options.actionsBox ?
  592. '<div class="bs-actionsbox">' +
  593. '<div class="btn-group btn-group-sm btn-block">' +
  594. '<button type="button" class="actions-btn bs-select-all btn ' + classNames.BUTTONCLASS + '">' +
  595. this.options.selectAllText +
  596. '</button>' +
  597. '<button type="button" class="actions-btn bs-deselect-all btn ' + classNames.BUTTONCLASS + '">' +
  598. this.options.deselectAllText +
  599. '</button>' +
  600. '</div>' +
  601. '</div>'
  602. : '';
  603. var donebutton = this.multiple && this.options.doneButton ?
  604. '<div class="bs-donebutton">' +
  605. '<div class="btn-group btn-block">' +
  606. '<button type="button" class="btn btn-sm ' + classNames.BUTTONCLASS + '">' +
  607. this.options.doneButtonText +
  608. '</button>' +
  609. '</div>' +
  610. '</div>'
  611. : '';
  612. var drop =
  613. '<div class="dropdown bootstrap-select' + showTick + '">' +
  614. '<button type="button" class="' + this.options.styleBase + ' dropdown-toggle" ' + (this.options.display === 'static' ? 'data-display="static"' : '') + 'data-toggle="dropdown"' + autofocus + ' role="button">' +
  615. '<div class="filter-option">' +
  616. '<div class="filter-option-inner">' +
  617. '<div class="filter-option-inner-inner"></div>' +
  618. '</div> ' +
  619. '</div>' +
  620. (version.major === '4' ?
  621. '' :
  622. '<span class="bs-caret">' +
  623. this.options.template.caret +
  624. '</span>'
  625. ) +
  626. '</button>' +
  627. '<div class="' + classNames.MENU + ' ' + (version.major === '4' ? '' : classNames.SHOW) + '" role="combobox">' +
  628. header +
  629. searchbox +
  630. actionsbox +
  631. '<div class="inner ' + classNames.SHOW + '" role="listbox" aria-expanded="false" tabindex="-1">' +
  632. '<ul class="' + classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : '') + '">' +
  633. '</ul>' +
  634. '</div>' +
  635. donebutton +
  636. '</div>' +
  637. '</div>';
  638. return $(drop);
  639. },
  640. setPositionData: function () {
  641. this.selectpicker.view.canHighlight = [];
  642. for (var i = 0; i < this.selectpicker.current.data.length; i++) {
  643. var li = this.selectpicker.current.data[i],
  644. canHighlight = true;
  645. if (li.type === 'divider') {
  646. canHighlight = false;
  647. li.height = this.sizeInfo.dividerHeight;
  648. } else if (li.type === 'optgroup-label') {
  649. canHighlight = false;
  650. li.height = this.sizeInfo.dropdownHeaderHeight;
  651. } else {
  652. li.height = this.sizeInfo.liHeight;
  653. }
  654. if (li.disabled) canHighlight = false;
  655. this.selectpicker.view.canHighlight.push(canHighlight);
  656. li.position = (i === 0 ? 0 : this.selectpicker.current.data[i - 1].position) + li.height;
  657. }
  658. },
  659. isVirtual: function () {
  660. return (this.options.virtualScroll !== false) && this.selectpicker.main.elements.length >= this.options.virtualScroll || this.options.virtualScroll === true;
  661. },
  662. createView: function (isSearching, scrollTop) {
  663. scrollTop = scrollTop || 0;
  664. var that = this;
  665. this.selectpicker.current = isSearching ? this.selectpicker.search : this.selectpicker.main;
  666. var $lis;
  667. var active = [];
  668. var selected;
  669. var prevActive;
  670. var activeIndex;
  671. var prevActiveIndex;
  672. this.setPositionData();
  673. scroll(scrollTop, true);
  674. this.$menuInner.off('scroll.createView').on('scroll.createView', function (e, updateValue) {
  675. if (!that.noScroll) scroll(this.scrollTop, updateValue);
  676. that.noScroll = false;
  677. });
  678. function scroll(scrollTop, init) {
  679. var size = that.selectpicker.current.elements.length,
  680. chunks = [],
  681. chunkSize,
  682. chunkCount,
  683. firstChunk,
  684. lastChunk,
  685. currentChunk = undefined,
  686. prevPositions,
  687. positionIsDifferent,
  688. previousElements,
  689. menuIsDifferent = true,
  690. isVirtual = that.isVirtual();
  691. that.selectpicker.view.scrollTop = scrollTop;
  692. if (isVirtual === true) {
  693. // if an option that is encountered that is wider than the current menu width, update the menu width accordingly
  694. if (that.sizeInfo.hasScrollBar && that.$menu[0].offsetWidth > that.sizeInfo.totalMenuWidth) {
  695. that.sizeInfo.menuWidth = that.$menu[0].offsetWidth;
  696. that.sizeInfo.totalMenuWidth = that.sizeInfo.menuWidth + that.sizeInfo.scrollBarWidth;
  697. that.$menu.css('min-width', that.sizeInfo.menuWidth);
  698. }
  699. }
  700. chunkSize = Math.ceil(that.sizeInfo.menuInnerHeight / that.sizeInfo.liHeight * 1.5); // number of options in a chunk
  701. chunkCount = Math.round(size / chunkSize) || 1; // number of chunks
  702. for (var i = 0; i < chunkCount; i++) {
  703. var end_of_chunk = (i + 1) * chunkSize;
  704. if (i === chunkCount - 1) {
  705. end_of_chunk = size;
  706. }
  707. chunks[i] = [
  708. (i) * chunkSize + (!i ? 0 : 1),
  709. end_of_chunk
  710. ];
  711. if (!size) break;
  712. if (currentChunk === undefined && scrollTop <= that.selectpicker.current.data[end_of_chunk - 1].position - that.sizeInfo.menuInnerHeight) {
  713. currentChunk = i;
  714. }
  715. }
  716. if (currentChunk === undefined) currentChunk = 0;
  717. prevPositions = [that.selectpicker.view.position0, that.selectpicker.view.position1];
  718. // always display previous, current, and next chunks
  719. firstChunk = Math.max(0, currentChunk - 1);
  720. lastChunk = Math.min(chunkCount - 1, currentChunk + 1);
  721. that.selectpicker.view.position0 = Math.max(0, chunks[firstChunk][0]) || 0;
  722. that.selectpicker.view.position1 = Math.min(size, chunks[lastChunk][1]) || 0;
  723. positionIsDifferent = prevPositions[0] !== that.selectpicker.view.position0 || prevPositions[1] !== that.selectpicker.view.position1;
  724. if (that.activeIndex !== undefined) {
  725. prevActive = that.selectpicker.current.elements[that.selectpicker.current.map.newIndex[that.prevActiveIndex]];
  726. active = that.selectpicker.current.elements[that.selectpicker.current.map.newIndex[that.activeIndex]];
  727. selected = that.selectpicker.current.elements[that.selectpicker.current.map.newIndex[that.selectedIndex]];
  728. if (init) {
  729. if (that.activeIndex !== that.selectedIndex) {
  730. active.classList.remove('active');
  731. if (active.firstChild) active.firstChild.classList.remove('active');
  732. }
  733. that.activeIndex = undefined;
  734. }
  735. if (that.activeIndex && that.activeIndex !== that.selectedIndex && selected && selected.length) {
  736. selected.classList.remove('active');
  737. if (selected.firstChild) selected.firstChild.classList.remove('active');
  738. }
  739. }
  740. if (that.prevActiveIndex !== undefined && that.prevActiveIndex !== that.activeIndex && that.prevActiveIndex !== that.selectedIndex && prevActive && prevActive.length) {
  741. prevActive.classList.remove('active');
  742. if (prevActive.firstChild) prevActive.firstChild.classList.remove('active');
  743. }
  744. if (init || positionIsDifferent) {
  745. previousElements = that.selectpicker.view.visibleElements ? that.selectpicker.view.visibleElements.slice() : [];
  746. that.selectpicker.view.visibleElements = that.selectpicker.current.elements.slice(that.selectpicker.view.position0, that.selectpicker.view.position1);
  747. that.setOptionStatus();
  748. // if searching, check to make sure the list has actually been updated before updating DOM
  749. // this prevents unnecessary repaints
  750. if ( isSearching || (isVirtual === false && init) ) menuIsDifferent = !isEqual(previousElements, that.selectpicker.view.visibleElements);
  751. // if virtual scroll is disabled and not searching,
  752. // menu should never need to be updated more than once
  753. if ( (init || isVirtual === true) && menuIsDifferent ) {
  754. var menuInner = that.$menuInner[0],
  755. menuFragment = document.createDocumentFragment(),
  756. emptyMenu = menuInner.firstChild.cloneNode(false),
  757. marginTop,
  758. marginBottom,
  759. elements = isVirtual === true ? that.selectpicker.view.visibleElements : that.selectpicker.current.elements;
  760. // replace the existing UL with an empty one - this is faster than $.empty()
  761. menuInner.replaceChild(emptyMenu, menuInner.firstChild);
  762. for (var i = 0, visibleElementsLen = elements.length; i < visibleElementsLen; i++) {
  763. menuFragment.appendChild(elements[i]);
  764. }
  765. if (isVirtual === true) {
  766. marginTop = (that.selectpicker.view.position0 === 0 ? 0 : that.selectpicker.current.data[that.selectpicker.view.position0 - 1].position),
  767. 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);
  768. menuInner.firstChild.style.marginTop = marginTop + 'px';
  769. menuInner.firstChild.style.marginBottom = marginBottom + 'px';
  770. }
  771. menuInner.firstChild.appendChild(menuFragment);
  772. }
  773. }
  774. that.prevActiveIndex = that.activeIndex;
  775. if (!that.options.liveSearch) {
  776. that.$menuInner.focus();
  777. } else if (isSearching && init) {
  778. var index = 0,
  779. newActive;
  780. if (!that.selectpicker.view.canHighlight[index]) {
  781. index = 1 + that.selectpicker.view.canHighlight.slice(1).indexOf(true);
  782. }
  783. newActive = that.selectpicker.view.visibleElements[index];
  784. if (that.selectpicker.view.currentActive) {
  785. that.selectpicker.view.currentActive.classList.remove('active');
  786. if (that.selectpicker.view.currentActive.firstChild) that.selectpicker.view.currentActive.firstChild.classList.remove('active');
  787. }
  788. if (newActive) {
  789. newActive.classList.add('active');
  790. if (newActive.firstChild) newActive.firstChild.classList.add('active');
  791. }
  792. that.activeIndex = that.selectpicker.current.map.originalIndex[index];
  793. }
  794. }
  795. $(window).off('resize.createView').on('resize.createView', function () {
  796. scroll(that.$menuInner[0].scrollTop);
  797. });
  798. },
  799. createLi: function () {
  800. var that = this,
  801. mainElements = [],
  802. widestOption,
  803. availableOptionsCount = 0,
  804. widestOptionLength = 0,
  805. mainData = [],
  806. optID = 0,
  807. headerIndex = 0,
  808. liIndex = -1; // increment liIndex whenever a new <li> element is created to ensure newIndex is correct
  809. if (!this.selectpicker.view.titleOption) this.selectpicker.view.titleOption = document.createElement('option');
  810. var elementTemplates = {
  811. span: document.createElement('span'),
  812. subtext: document.createElement('small'),
  813. a: document.createElement('a'),
  814. li: document.createElement('li'),
  815. whitespace: document.createTextNode("\u00A0")
  816. },
  817. checkMark = elementTemplates.span.cloneNode(false),
  818. fragment = document.createDocumentFragment();
  819. checkMark.className = that.options.iconBase + ' ' + that.options.tickIcon + ' check-mark';
  820. elementTemplates.a.appendChild(checkMark);
  821. elementTemplates.a.setAttribute('role', 'option');
  822. elementTemplates.subtext.className = 'text-muted';
  823. elementTemplates.text = elementTemplates.span.cloneNode(false);
  824. elementTemplates.text.className = 'text';
  825. // Helper functions
  826. /**
  827. * @param content
  828. * @param [index]
  829. * @param [classes]
  830. * @param [optgroup]
  831. * @returns {HTMLElement}
  832. */
  833. var generateLI = function (content, index, classes, optgroup) {
  834. var li = elementTemplates.li.cloneNode(false);
  835. if (content) {
  836. if (content.nodeType === 1 || content.nodeType === 11) {
  837. li.appendChild(content);
  838. } else {
  839. li.innerHTML = content;
  840. }
  841. }
  842. if (typeof classes !== 'undefined' && '' !== classes) li.className = classes;
  843. if (typeof optgroup !== 'undefined' && null !== optgroup) li.classList.add('optgroup-' + optgroup);
  844. return li;
  845. };
  846. /**
  847. * @param text
  848. * @param [classes]
  849. * @param [inline]
  850. * @returns {string}
  851. */
  852. var generateA = function (text, classes, inline) {
  853. var a = elementTemplates.a.cloneNode(true);
  854. if (text) {
  855. if (text.nodeType === 11) {
  856. a.appendChild(text);
  857. } else {
  858. a.insertAdjacentHTML('beforeend', text);
  859. }
  860. }
  861. if (typeof classes !== 'undefined' & '' !== classes) a.className = classes;
  862. if (version.major === '4') a.classList.add('dropdown-item');
  863. if (inline) a.setAttribute('style', inline);
  864. return a;
  865. };
  866. var generateText = function (options) {
  867. var textElement = elementTemplates.text.cloneNode(false),
  868. optionSubtextElement,
  869. optionIconElement;
  870. if (options.optionContent) {
  871. textElement.innerHTML = options.optionContent;
  872. } else {
  873. textElement.textContent = options.text;
  874. if (options.optionIcon) {
  875. var whitespace = elementTemplates.whitespace.cloneNode(false);
  876. optionIconElement = elementTemplates.span.cloneNode(false);
  877. optionIconElement.className = that.options.iconBase + ' ' + options.optionIcon;
  878. fragment.appendChild(optionIconElement);
  879. fragment.appendChild(whitespace);
  880. }
  881. if (options.optionSubtext) {
  882. optionSubtextElement = elementTemplates.subtext.cloneNode(false);
  883. optionSubtextElement.innerHTML = options.optionSubtext;
  884. textElement.appendChild(optionSubtextElement);
  885. }
  886. }
  887. fragment.appendChild(textElement);
  888. return fragment;
  889. };
  890. var generateLabel = function (options) {
  891. var labelTextElement = elementTemplates.text.cloneNode(false),
  892. labelSubtextElement,
  893. labelIconElement;
  894. labelTextElement.innerHTML = options.labelEscaped;
  895. if (options.labelIcon) {
  896. var whitespace = elementTemplates.whitespace.cloneNode(false);
  897. labelIconElement = elementTemplates.span.cloneNode(false);
  898. labelIconElement.className = that.options.iconBase + ' ' + options.labelIcon;
  899. fragment.appendChild(labelIconElement);
  900. fragment.appendChild(whitespace);
  901. }
  902. if (options.labelSubtext) {
  903. labelSubtextElement = elementTemplates.subtext.cloneNode(false);
  904. labelSubtextElement.textContent = options.labelSubtext;
  905. labelTextElement.appendChild(labelSubtextElement);
  906. }
  907. fragment.appendChild(labelTextElement);
  908. return fragment;
  909. }
  910. if (this.options.title && !this.multiple) {
  911. // this option doesn't create a new <li> element, but does add a new option, so liIndex is decreased
  912. // since newIndex is recalculated on every refresh, liIndex needs to be decreased even if the titleOption is already appended
  913. liIndex--;
  914. var element = this.$element[0],
  915. isSelected = false,
  916. titleNotAppended = !this.selectpicker.view.titleOption.parentNode;
  917. if (titleNotAppended) {
  918. // Use native JS to prepend option (faster)
  919. this.selectpicker.view.titleOption.className = 'bs-title-option';
  920. this.selectpicker.view.titleOption.value = '';
  921. // Check if selected or data-selected attribute is already set on an option. If not, select the titleOption option.
  922. // the selected item may have been changed by user or programmatically before the bootstrap select plugin runs,
  923. // if so, the select will have the data-selected attribute
  924. var $opt = $(element.options[element.selectedIndex]);
  925. isSelected = $opt.attr('selected') === undefined && this.$element.data('selected') === undefined;
  926. }
  927. if (titleNotAppended || this.selectpicker.view.titleOption.index !== 0) {
  928. element.insertBefore(this.selectpicker.view.titleOption, element.firstChild);
  929. }
  930. // Set selected *after* appending to select,
  931. // otherwise the option doesn't get selected in IE
  932. // set using selectedIndex, as setting the selected attr to true here doesn't work in IE11
  933. if (isSelected) element.selectedIndex = 0;
  934. }
  935. var $selectOptions = this.$element.find('option');
  936. $selectOptions.each(function (index) {
  937. var $this = $(this);
  938. liIndex++;
  939. if ($this.hasClass('bs-title-option')) return;
  940. var thisData = $this.data();
  941. // Get the class and text for the option
  942. var optionClass = this.className || '',
  943. inline = htmlEscape(this.style.cssText),
  944. optionContent = thisData.content,
  945. text = this.textContent,
  946. tokens = thisData.tokens,
  947. subtext = thisData.subtext,
  948. icon = thisData.icon,
  949. $parent = $this.parent(),
  950. parent = $parent[0],
  951. isOptgroup = parent.tagName === 'OPTGROUP',
  952. isOptgroupDisabled = isOptgroup && parent.disabled,
  953. isDisabled = this.disabled || isOptgroupDisabled,
  954. prevHiddenIndex,
  955. showDivider = this.previousElementSibling && this.previousElementSibling.tagName === 'OPTGROUP',
  956. textElement;
  957. var parentData = $parent.data();
  958. if (thisData.hidden === true || that.options.hideDisabled && (isDisabled && !isOptgroup || isOptgroupDisabled)) {
  959. // set prevHiddenIndex - the index of the first hidden option in a group of hidden options
  960. // used to determine whether or not a divider should be placed after an optgroup if there are
  961. // hidden options between the optgroup and the first visible option
  962. prevHiddenIndex = thisData.prevHiddenIndex;
  963. $this.next().data('prevHiddenIndex', (prevHiddenIndex !== undefined ? prevHiddenIndex : index));
  964. liIndex--;
  965. // if previous element is not an optgroup
  966. if (!showDivider) {
  967. if (prevHiddenIndex !== undefined) {
  968. // select the element **before** the first hidden element in the group
  969. var prevHidden = $selectOptions[prevHiddenIndex].previousElementSibling;
  970. if (prevHidden && prevHidden.tagName === 'OPTGROUP' && !prevHidden.disabled) {
  971. showDivider = true;
  972. }
  973. }
  974. }
  975. if (showDivider && mainData[mainData.length - 1].type !== 'divider') {
  976. liIndex++;
  977. mainElements.push(
  978. generateLI(
  979. false,
  980. null,
  981. classNames.DIVIDER,
  982. optID + 'div'
  983. )
  984. );
  985. mainData.push({
  986. type: 'divider',
  987. optID: optID
  988. });
  989. }
  990. return;
  991. }
  992. if (isOptgroup && thisData.divider !== true) {
  993. if (that.options.hideDisabled && isDisabled) {
  994. if (parentData.allOptionsDisabled === undefined) {
  995. var $options = $parent.children();
  996. $parent.data('allOptionsDisabled', $options.filter(':disabled').length === $options.length);
  997. }
  998. if ($parent.data('allOptionsDisabled')) {
  999. liIndex--;
  1000. return;
  1001. }
  1002. }
  1003. var optGroupClass = ' ' + parent.className || '';
  1004. if (!this.previousElementSibling) { // Is it the first option of the optgroup?
  1005. optID += 1;
  1006. // Get the opt group label
  1007. var label = parent.label,
  1008. labelEscaped = htmlEscape(label),
  1009. labelSubtext = parentData.subtext,
  1010. labelIcon = parentData.icon;
  1011. if (index !== 0 && mainElements.length > 0) { // Is it NOT the first option of the select && are there elements in the dropdown?
  1012. liIndex++;
  1013. mainElements.push(
  1014. generateLI(
  1015. false,
  1016. null,
  1017. classNames.DIVIDER,
  1018. optID + 'div'
  1019. )
  1020. );
  1021. mainData.push({
  1022. type: 'divider',
  1023. optID: optID
  1024. });
  1025. }
  1026. liIndex++;
  1027. var labelElement = generateLabel({
  1028. labelEscaped: labelEscaped,
  1029. labelSubtext: labelSubtext,
  1030. labelIcon: labelIcon
  1031. });
  1032. mainElements.push(generateLI(labelElement, null, 'dropdown-header' + optGroupClass, optID));
  1033. mainData.push({
  1034. content: labelEscaped,
  1035. subtext: labelSubtext,
  1036. type: 'optgroup-label',
  1037. optID: optID
  1038. });
  1039. headerIndex = liIndex - 1;
  1040. }
  1041. if (that.options.hideDisabled && isDisabled || thisData.hidden === true) {
  1042. liIndex--;
  1043. return;
  1044. }
  1045. textElement = generateText({
  1046. text: text,
  1047. optionContent: optionContent,
  1048. optionSubtext: subtext,
  1049. optionIcon: icon
  1050. });
  1051. mainElements.push(generateLI(generateA(textElement, 'opt ' + optionClass + optGroupClass, inline), index, '', optID));
  1052. mainData.push({
  1053. content: optionContent || text,
  1054. subtext: subtext,
  1055. tokens: tokens,
  1056. type: 'option',
  1057. optID: optID,
  1058. headerIndex: headerIndex,
  1059. lastIndex: headerIndex + parent.childElementCount,
  1060. originalIndex: index,
  1061. data: thisData
  1062. });
  1063. availableOptionsCount++;
  1064. } else if (thisData.divider === true) {
  1065. mainElements.push(generateLI(false, index, classNames.DIVIDER));
  1066. mainData.push({
  1067. type: 'divider',
  1068. originalIndex: index,
  1069. data: thisData
  1070. });
  1071. } else {
  1072. // if previous element is not an optgroup and hideDisabled is true
  1073. if (!showDivider && that.options.hideDisabled) {
  1074. prevHiddenIndex = thisData.prevHiddenIndex;
  1075. if (prevHiddenIndex !== undefined) {
  1076. // select the element **before** the first hidden element in the group
  1077. var prevHidden = $selectOptions[prevHiddenIndex].previousElementSibling;
  1078. if (prevHidden && prevHidden.tagName === 'OPTGROUP' && !prevHidden.disabled) {
  1079. showDivider = true;
  1080. }
  1081. }
  1082. }
  1083. if (showDivider && mainData[mainData.length - 1].type !== 'divider') {
  1084. liIndex++;
  1085. mainElements.push(
  1086. generateLI(
  1087. false,
  1088. null,
  1089. classNames.DIVIDER,
  1090. optID + 'div'
  1091. )
  1092. );
  1093. mainData.push({
  1094. type: 'divider',
  1095. optID: optID
  1096. });
  1097. }
  1098. textElement = generateText({
  1099. text: text,
  1100. optionContent: optionContent,
  1101. optionSubtext: subtext,
  1102. optionIcon: icon
  1103. });
  1104. mainElements.push(generateLI(generateA(textElement, optionClass, inline), index));
  1105. mainData.push({
  1106. content: optionContent || text,
  1107. subtext: subtext,
  1108. tokens: tokens,
  1109. type: 'option',
  1110. originalIndex: index,
  1111. data: thisData
  1112. });
  1113. availableOptionsCount++;
  1114. }
  1115. that.selectpicker.main.map.newIndex[index] = liIndex;
  1116. that.selectpicker.main.map.originalIndex[liIndex] = index;
  1117. // get the most recent option info added to mainData
  1118. var _mainDataLast = mainData[mainData.length - 1];
  1119. _mainDataLast.disabled = isDisabled;
  1120. var combinedLength = 0;
  1121. // count the number of characters in the option - not perfect, but should work in most cases
  1122. if (_mainDataLast.content) combinedLength += _mainDataLast.content.length;
  1123. if (_mainDataLast.subtext) combinedLength += _mainDataLast.subtext.length;
  1124. // if there is an icon, ensure this option's width is checked
  1125. if (icon) combinedLength += 1;
  1126. if (combinedLength > widestOptionLength) {
  1127. widestOptionLength = combinedLength;
  1128. // guess which option is the widest
  1129. // use this when calculating menu width
  1130. // not perfect, but it's fast, and the width will be updating accordingly when scrolling
  1131. widestOption = mainElements[mainElements.length - 1];
  1132. }
  1133. });
  1134. this.selectpicker.main.elements = mainElements;
  1135. this.selectpicker.main.data = mainData;
  1136. this.selectpicker.current = this.selectpicker.main;
  1137. this.selectpicker.view.widestOption = widestOption;
  1138. this.selectpicker.view.availableOptionsCount = availableOptionsCount; // faster way to get # of available options without filter
  1139. },
  1140. findLis: function () {
  1141. return this.$menuInner.find('.inner > li');
  1142. },
  1143. render: function () {
  1144. var that = this,
  1145. $selectOptions = this.$element.find('option'),
  1146. selectedItems = [],
  1147. selectedItemsInTitle = [];
  1148. this.togglePlaceholder();
  1149. this.tabIndex();
  1150. for (var i = 0, len = this.selectpicker.main.elements.length; i < len; i++) {
  1151. var index = this.selectpicker.main.map.originalIndex[i],
  1152. option = $selectOptions[index];
  1153. if (option && option.selected) {
  1154. selectedItems.push(option);
  1155. if (selectedItemsInTitle.length < 100 && that.options.selectedTextFormat !== 'count' || selectedItems.length === 1) {
  1156. if (that.options.hideDisabled && (option.disabled || option.parentNode.tagName === 'OPTGROUP' && option.parentNode.disabled)) return;
  1157. var thisData = this.selectpicker.main.data[i].data,
  1158. icon = thisData.icon && that.options.showIcon ? '<i class="' + that.options.iconBase + ' ' + thisData.icon + '"></i> ' : '',
  1159. subtext,
  1160. titleItem;
  1161. if (that.options.showSubtext && thisData.subtext && !that.multiple) {
  1162. subtext = ' <small class="text-muted">' + thisData.subtext + '</small>';
  1163. } else {
  1164. subtext = '';
  1165. }
  1166. if (option.title) {
  1167. titleItem = option.title;
  1168. } else if (thisData.content && that.options.showContent) {
  1169. titleItem = thisData.content.toString();
  1170. } else {
  1171. titleItem = icon + option.innerHTML.trim() + subtext;
  1172. }
  1173. selectedItemsInTitle.push(titleItem);
  1174. }
  1175. }
  1176. }
  1177. //Fixes issue in IE10 occurring when no default option is selected and at least one option is disabled
  1178. //Convert all the values into a comma delimited string
  1179. var title = !this.multiple ? selectedItemsInTitle[0] : selectedItemsInTitle.join(this.options.multipleSeparator);
  1180. // add ellipsis
  1181. if (selectedItems.length > 50) title += '...';
  1182. // If this is a multiselect, and selectedTextFormat is count, then show 1 of 2 selected etc..
  1183. if (this.multiple && this.options.selectedTextFormat.indexOf('count') !== -1) {
  1184. var max = this.options.selectedTextFormat.split('>');
  1185. if ((max.length > 1 && selectedItems.length > max[1]) || (max.length === 1 && selectedItems.length >= 2)) {
  1186. var totalCount = this.selectpicker.view.availableOptionsCount,
  1187. tr8nText = (typeof this.options.countSelectedText === 'function') ? this.options.countSelectedText(selectedItems.length, totalCount) : this.options.countSelectedText;
  1188. title = tr8nText.replace('{0}', selectedItems.length.toString()).replace('{1}', totalCount.toString());
  1189. }
  1190. }
  1191. if (this.options.title == undefined) {
  1192. // use .attr to ensure undefined is returned if title attribute is not set
  1193. this.options.title = this.$element.attr('title');
  1194. }
  1195. if (this.options.selectedTextFormat == 'static') {
  1196. title = this.options.title;
  1197. }
  1198. //If we dont have a title, then use the default, or if nothing is set at all, use the not selected text
  1199. if (!title) {
  1200. title = typeof this.options.title !== 'undefined' ? this.options.title : this.options.noneSelectedText;
  1201. }
  1202. //strip all HTML tags and trim the result, then unescape any escaped tags
  1203. this.$button[0].title = htmlUnescape(title.replace(/<[^>]*>?/g, '').trim());
  1204. this.$button.find('.filter-option-inner-inner')[0].innerHTML = title;
  1205. this.$element.trigger('rendered.bs.select');
  1206. },
  1207. /**
  1208. * @param [style]
  1209. * @param [status]
  1210. */
  1211. setStyle: function (style, status) {
  1212. if (this.$element.attr('class')) {
  1213. this.$newElement.addClass(this.$element.attr('class').replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi, ''));
  1214. }
  1215. var buttonClass = style ? style : this.options.style;
  1216. if (status == 'add') {
  1217. this.$button.addClass(buttonClass);
  1218. } else if (status == 'remove') {
  1219. this.$button.removeClass(buttonClass);
  1220. } else {
  1221. this.$button.removeClass(this.options.style);
  1222. this.$button.addClass(buttonClass);
  1223. }
  1224. },
  1225. liHeight: function (refresh) {
  1226. if (!refresh && (this.options.size === false || this.sizeInfo)) return;
  1227. if (!this.sizeInfo) this.sizeInfo = {};
  1228. var newElement = document.createElement('div'),
  1229. menu = document.createElement('div'),
  1230. menuInner = document.createElement('div'),
  1231. menuInnerInner = document.createElement('ul'),
  1232. divider = document.createElement('li'),
  1233. dropdownHeader = document.createElement('li'),
  1234. li = document.createElement('li'),
  1235. a = document.createElement('a'),
  1236. text = document.createElement('span'),
  1237. header = this.options.header && this.$menu.find('.' + classNames.POPOVERHEADER).length > 0 ? this.$menu.find('.' + classNames.POPOVERHEADER)[0].cloneNode(true) : null,
  1238. search = this.options.liveSearch ? document.createElement('div') : null,
  1239. actions = this.options.actionsBox && this.multiple && this.$menu.find('.bs-actionsbox').length > 0 ? this.$menu.find('.bs-actionsbox')[0].cloneNode(true) : null,
  1240. doneButton = this.options.doneButton && this.multiple && this.$menu.find('.bs-donebutton').length > 0 ? this.$menu.find('.bs-donebutton')[0].cloneNode(true) : null;
  1241. this.sizeInfo.selectWidth = this.$newElement[0].offsetWidth;
  1242. text.className = 'text';
  1243. a.className = 'dropdown-item ' + this.$element.find('option')[0].className;
  1244. newElement.className = this.$menu[0].parentNode.className + ' ' + classNames.SHOW;
  1245. newElement.style.width = this.sizeInfo.selectWidth + 'px';
  1246. if (this.options.width === 'auto') menu.style.minWidth = 0;
  1247. menu.className = classNames.MENU + ' ' + classNames.SHOW;
  1248. menuInner.className = 'inner ' + classNames.SHOW;
  1249. menuInnerInner.className = classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : '');
  1250. divider.className = classNames.DIVIDER;
  1251. dropdownHeader.className = 'dropdown-header';
  1252. text.appendChild(document.createTextNode('Inner text'));
  1253. a.appendChild(text);
  1254. li.appendChild(a);
  1255. dropdownHeader.appendChild(text.cloneNode(true));
  1256. if (this.selectpicker.view.widestOption) {
  1257. menuInnerInner.appendChild(this.selectpicker.view.widestOption.cloneNode(true));
  1258. }
  1259. menuInnerInner.appendChild(li);
  1260. menuInnerInner.appendChild(divider);
  1261. menuInnerInner.appendChild(dropdownHeader);
  1262. if (header) menu.appendChild(header);
  1263. if (search) {
  1264. var input = document.createElement('input');
  1265. search.className = 'bs-searchbox';
  1266. input.className = 'form-control';
  1267. search.appendChild(input);
  1268. menu.appendChild(search);
  1269. }
  1270. if (actions) menu.appendChild(actions);
  1271. menuInner.appendChild(menuInnerInner);
  1272. menu.appendChild(menuInner);
  1273. if (doneButton) menu.appendChild(doneButton);
  1274. newElement.appendChild(menu);
  1275. document.body.appendChild(newElement);
  1276. var liHeight = a.offsetHeight,
  1277. dropdownHeaderHeight = dropdownHeader ? dropdownHeader.offsetHeight : 0,
  1278. headerHeight = header ? header.offsetHeight : 0,
  1279. searchHeight = search ? search.offsetHeight : 0,
  1280. actionsHeight = actions ? actions.offsetHeight : 0,
  1281. doneButtonHeight = doneButton ? doneButton.offsetHeight : 0,
  1282. dividerHeight = $(divider).outerHeight(true),
  1283. // fall back to jQuery if getComputedStyle is not supported
  1284. menuStyle = window.getComputedStyle ? window.getComputedStyle(menu) : false,
  1285. menuWidth = menu.offsetWidth,
  1286. $menu = menuStyle ? null : $(menu),
  1287. menuPadding = {
  1288. vert: toInteger(menuStyle ? menuStyle.paddingTop : $menu.css('paddingTop')) +
  1289. toInteger(menuStyle ? menuStyle.paddingBottom : $menu.css('paddingBottom')) +
  1290. toInteger(menuStyle ? menuStyle.borderTopWidth : $menu.css('borderTopWidth')) +
  1291. toInteger(menuStyle ? menuStyle.borderBottomWidth : $menu.css('borderBottomWidth')),
  1292. horiz: toInteger(menuStyle ? menuStyle.paddingLeft : $menu.css('paddingLeft')) +
  1293. toInteger(menuStyle ? menuStyle.paddingRight : $menu.css('paddingRight')) +
  1294. toInteger(menuStyle ? menuStyle.borderLeftWidth : $menu.css('borderLeftWidth')) +
  1295. toInteger(menuStyle ? menuStyle.borderRightWidth : $menu.css('borderRightWidth'))
  1296. },
  1297. menuExtras = {
  1298. vert: menuPadding.vert +
  1299. toInteger(menuStyle ? menuStyle.marginTop : $menu.css('marginTop')) +
  1300. toInteger(menuStyle ? menuStyle.marginBottom : $menu.css('marginBottom')) + 2,
  1301. horiz: menuPadding.horiz +
  1302. toInteger(menuStyle ? menuStyle.marginLeft : $menu.css('marginLeft')) +
  1303. toInteger(menuStyle ? menuStyle.marginRight : $menu.css('marginRight')) + 2
  1304. },
  1305. scrollBarWidth;
  1306. menuInner.style.overflowY = 'scroll';
  1307. scrollBarWidth = menu.offsetWidth - menuWidth;
  1308. document.body.removeChild(newElement);
  1309. this.sizeInfo.liHeight = liHeight;
  1310. this.sizeInfo.dropdownHeaderHeight = dropdownHeaderHeight;
  1311. this.sizeInfo.headerHeight = headerHeight;
  1312. this.sizeInfo.searchHeight = searchHeight;
  1313. this.sizeInfo.actionsHeight = actionsHeight;
  1314. this.sizeInfo.doneButtonHeight = doneButtonHeight;
  1315. this.sizeInfo.dividerHeight = dividerHeight;
  1316. this.sizeInfo.menuPadding = menuPadding;
  1317. this.sizeInfo.menuExtras = menuExtras;
  1318. this.sizeInfo.menuWidth = menuWidth;
  1319. this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth;
  1320. this.sizeInfo.scrollBarWidth = scrollBarWidth;
  1321. this.sizeInfo.selectHeight = this.$newElement[0].offsetHeight;
  1322. this.setPositionData();
  1323. },
  1324. getSelectPosition: function () {
  1325. var that = this,
  1326. $window = $(window),
  1327. pos = that.$newElement.offset(),
  1328. $container = $(that.options.container),
  1329. containerPos;
  1330. if (that.options.container && !$container.is('body')) {
  1331. containerPos = $container.offset();
  1332. containerPos.top += parseInt($container.css('borderTopWidth'));
  1333. containerPos.left += parseInt($container.css('borderLeftWidth'));
  1334. } else {
  1335. containerPos = { top: 0, left: 0 };
  1336. }
  1337. var winPad = that.options.windowPadding;
  1338. this.sizeInfo.selectOffsetTop = pos.top - containerPos.top - $window.scrollTop();
  1339. this.sizeInfo.selectOffsetBot = $window.height() - this.sizeInfo.selectOffsetTop - this.sizeInfo['selectHeight'] - containerPos.top - winPad[2];
  1340. this.sizeInfo.selectOffsetLeft = pos.left - containerPos.left - $window.scrollLeft();
  1341. this.sizeInfo.selectOffsetRight = $window.width() - this.sizeInfo.selectOffsetLeft - this.sizeInfo['selectWidth'] - containerPos.left - winPad[1];
  1342. this.sizeInfo.selectOffsetTop -= winPad[0];
  1343. this.sizeInfo.selectOffsetLeft -= winPad[3];
  1344. },
  1345. setMenuSize: function (isAuto) {
  1346. this.getSelectPosition();
  1347. var selectWidth = this.sizeInfo['selectWidth'],
  1348. liHeight = this.sizeInfo['liHeight'],
  1349. headerHeight = this.sizeInfo['headerHeight'],
  1350. searchHeight = this.sizeInfo['searchHeight'],
  1351. actionsHeight = this.sizeInfo['actionsHeight'],
  1352. doneButtonHeight = this.sizeInfo['doneButtonHeight'],
  1353. divHeight = this.sizeInfo['dividerHeight'],
  1354. menuPadding = this.sizeInfo['menuPadding'],
  1355. menuInnerHeight,
  1356. menuHeight,
  1357. divLength = 0,
  1358. minHeight,
  1359. _minHeight,
  1360. maxHeight,
  1361. menuInnerMinHeight,
  1362. estimate;
  1363. if (this.options.dropupAuto) {
  1364. // Get the estimated height of the menu without scrollbars.
  1365. // This is useful for smaller menus, where there might be plenty of room
  1366. // below the button without setting dropup, but we can't know
  1367. // the exact height of the menu until createView is called later
  1368. estimate = liHeight * this.selectpicker.current.elements.length + menuPadding.vert;
  1369. this.$newElement.toggleClass(classNames.DROPUP, this.sizeInfo.selectOffsetTop - this.sizeInfo.selectOffsetBot > this.sizeInfo.menuExtras.vert && estimate + this.sizeInfo.menuExtras.vert + 50 > this.sizeInfo.selectOffsetBot);
  1370. }
  1371. if (this.options.size === 'auto') {
  1372. _minHeight = this.selectpicker.current.elements.length > 3 ? this.sizeInfo.liHeight * 3 + this.sizeInfo.menuExtras.vert - 2 : 0;
  1373. menuHeight = this.sizeInfo.selectOffsetBot - this.sizeInfo.menuExtras.vert;
  1374. minHeight = _minHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
  1375. menuInnerMinHeight = Math.max(_minHeight - menuPadding.vert, 0);
  1376. if (this.$newElement.hasClass(classNames.DROPUP)) {
  1377. menuHeight = this.sizeInfo.selectOffsetTop - this.sizeInfo.menuExtras.vert;
  1378. }
  1379. maxHeight = menuHeight;
  1380. menuInnerHeight = menuHeight - headerHeight - searchHeight - actionsHeight - doneButtonHeight - menuPadding.vert;
  1381. } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
  1382. for (var i = 0; i < this.options.size; i++) {
  1383. if (this.selectpicker.current.data[i].type === 'divider') divLength++;
  1384. }
  1385. menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding.vert;
  1386. menuInnerHeight = menuHeight - menuPadding.vert;
  1387. maxHeight = menuHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
  1388. minHeight = menuInnerMinHeight = '';
  1389. }
  1390. if (this.options.dropdownAlignRight === 'auto') {
  1391. this.$menu.toggleClass(classNames.MENURIGHT, this.sizeInfo.selectOffsetLeft > this.sizeInfo.selectOffsetRight && this.sizeInfo.selectOffsetRight < (this.$menu[0].offsetWidth - selectWidth));
  1392. }
  1393. this.$menu.css({
  1394. 'max-height': maxHeight + 'px',
  1395. 'overflow': 'hidden',
  1396. 'min-height': minHeight + 'px'
  1397. });
  1398. this.$menuInner.css({
  1399. 'max-height': menuInnerHeight + 'px',
  1400. 'overflow-y': 'auto',
  1401. 'min-height': menuInnerMinHeight + 'px'
  1402. });
  1403. this.sizeInfo['menuInnerHeight'] = menuInnerHeight;
  1404. if (this.selectpicker.current.data.length && this.selectpicker.current.data[this.selectpicker.current.data.length - 1].position > this.sizeInfo.menuInnerHeight) {
  1405. this.sizeInfo.hasScrollBar = true;
  1406. this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth + this.sizeInfo.scrollBarWidth;
  1407. this.$menu.css('min-width', this.sizeInfo.totalMenuWidth);
  1408. }
  1409. if (this.dropdown && this.dropdown._popper) this.dropdown._popper.update();
  1410. },
  1411. setSize: function (refresh) {
  1412. this.liHeight(refresh);
  1413. if (this.options.header) this.$menu.css('padding-top', 0);
  1414. if (this.options.size === false) return;
  1415. var that = this,
  1416. $window = $(window),
  1417. selectedIndex,
  1418. offset = 0;
  1419. this.setMenuSize();
  1420. if (this.options.size === 'auto') {
  1421. this.$searchbox.off('input.setMenuSize propertychange.setMenuSize').on('input.setMenuSize propertychange.setMenuSize', function() {
  1422. return that.setMenuSize();
  1423. });
  1424. $window.off('resize.setMenuSize scroll.setMenuSize').on('resize.setMenuSize scroll.setMenuSize', function() {
  1425. return that.setMenuSize();
  1426. });
  1427. } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
  1428. this.$searchbox.off('input.setMenuSize propertychange.setMenuSize');
  1429. $window.off('resize.setMenuSize scroll.setMenuSize');
  1430. }
  1431. if (refresh) {
  1432. offset = this.$menuInner[0].scrollTop;
  1433. } else if (!that.multiple) {
  1434. selectedIndex = that.selectpicker.main.map.newIndex[that.$element[0].selectedIndex];
  1435. if (typeof selectedIndex === 'number' && that.options.size !== false) {
  1436. offset = that.sizeInfo.liHeight * selectedIndex;
  1437. offset = offset - (that.sizeInfo.menuInnerHeight / 2) + (that.sizeInfo.liHeight / 2);
  1438. }
  1439. }
  1440. that.createView(false, offset);
  1441. },
  1442. setWidth: function () {
  1443. var that = this;
  1444. if (this.options.width === 'auto') {
  1445. requestAnimationFrame(function() {
  1446. that.$menu.css('min-width', '0');
  1447. that.liHeight();
  1448. that.setMenuSize();
  1449. // Get correct width if element is hidden
  1450. var $selectClone = that.$newElement.clone().appendTo('body'),
  1451. btnWidth = $selectClone.css('width', 'auto').children('button').outerWidth();
  1452. $selectClone.remove();
  1453. // Set width to whatever's larger, button title or longest option
  1454. that.sizeInfo.selectWidth = Math.max(that.sizeInfo.totalMenuWidth, btnWidth);
  1455. that.$newElement.css('width', that.sizeInfo.selectWidth + 'px');
  1456. });
  1457. } else if (this.options.width === 'fit') {
  1458. // Remove inline min-width so width can be changed from 'auto'
  1459. this.$menu.css('min-width', '');
  1460. this.$newElement.css('width', '').addClass('fit-width');
  1461. } else if (this.options.width) {
  1462. // Remove inline min-width so width can be changed from 'auto'
  1463. this.$menu.css('min-width', '');
  1464. this.$newElement.css('width', this.options.width);
  1465. } else {
  1466. // Remove inline min-width/width so width can be changed
  1467. this.$menu.css('min-width', '');
  1468. this.$newElement.css('width', '');
  1469. }
  1470. // Remove fit-width class if width is changed programmatically
  1471. if (this.$newElement.hasClass('fit-width') && this.options.width !== 'fit') {
  1472. this.$newElement.removeClass('fit-width');
  1473. }
  1474. },
  1475. selectPosition: function () {
  1476. this.$bsContainer = $('<div class="bs-container" />');
  1477. var that = this,
  1478. $container = $(this.options.container),
  1479. pos,
  1480. containerPos,
  1481. actualHeight,
  1482. getPlacement = function ($element) {
  1483. var containerPosition = {},
  1484. // fall back to dropdown's default display setting if display is not manually set
  1485. display = that.options.display || $.fn.dropdown.Constructor.Default.display;
  1486. that.$bsContainer.addClass($element.attr('class').replace(/form-control|fit-width/gi, '')).toggleClass(classNames.DROPUP, $element.hasClass(classNames.DROPUP));
  1487. pos = $element.offset();
  1488. if (!$container.is('body')) {
  1489. containerPos = $container.offset();
  1490. containerPos.top += parseInt($container.css('borderTopWidth')) - $container.scrollTop();
  1491. containerPos.left += parseInt($container.css('borderLeftWidth')) - $container.scrollLeft();
  1492. } else {
  1493. containerPos = { top: 0, left: 0 };
  1494. }
  1495. actualHeight = $element.hasClass(classNames.DROPUP) ? 0 : $element[0].offsetHeight;
  1496. // Bootstrap 4+ uses Popper for menu positioning
  1497. if (version.major < 4 || display === 'static') {
  1498. containerPosition['top'] = pos.top - containerPos.top + actualHeight;
  1499. containerPosition['left'] = pos.left - containerPos.left;
  1500. }
  1501. containerPosition['width'] = $element[0].offsetWidth;
  1502. that.$bsContainer.css(containerPosition);
  1503. };
  1504. this.$button.on('click.bs.dropdown.data-api', function () {
  1505. if (that.isDisabled()) {
  1506. return;
  1507. }
  1508. getPlacement(that.$newElement);
  1509. that.$bsContainer
  1510. .appendTo(that.options.container)
  1511. .toggleClass(classNames.SHOW, !that.$button.hasClass(classNames.SHOW))
  1512. .append(that.$menu);
  1513. });
  1514. $(window).on('resize scroll', function () {
  1515. getPlacement(that.$newElement);
  1516. });
  1517. this.$element.on('hide.bs.select', function () {
  1518. that.$menu.data('height', that.$menu.height());
  1519. that.$bsContainer.detach();
  1520. });
  1521. },
  1522. setOptionStatus: function () {
  1523. var that = this,
  1524. $selectOptions = this.$element.find('option');
  1525. that.noScroll = false;
  1526. if (that.selectpicker.view.visibleElements && that.selectpicker.view.visibleElements.length) {
  1527. for (var i = 0; i < that.selectpicker.view.visibleElements.length; i++) {
  1528. var index = that.selectpicker.current.map.originalIndex[i + that.selectpicker.view.position0], // faster than $(li).data('originalIndex')
  1529. option = $selectOptions[index];
  1530. if (option) {
  1531. var liIndex = this.selectpicker.main.map.newIndex[index],
  1532. li = this.selectpicker.main.elements[liIndex];
  1533. that.setDisabled(
  1534. index,
  1535. option.disabled || option.parentNode.tagName === 'OPTGROUP' && option.parentNode.disabled,
  1536. liIndex,
  1537. li
  1538. );
  1539. that.setSelected(
  1540. index,
  1541. option.selected,
  1542. liIndex,
  1543. li
  1544. );
  1545. }
  1546. }
  1547. }
  1548. },
  1549. /**
  1550. * @param {number} index - the index of the option that is being changed
  1551. * @param {boolean} selected - true if the option is being selected, false if being deselected
  1552. */
  1553. setSelected: function (index, selected, liIndex, li) {
  1554. var activeIndexIsSet = this.activeIndex !== undefined,
  1555. thisIsActive = this.activeIndex === index,
  1556. prevActiveIndex,
  1557. prevActive,
  1558. a,
  1559. // if current option is already active
  1560. // OR
  1561. // if the current option is being selected, it's NOT multiple, and
  1562. // activeIndex is undefined:
  1563. // - when the menu is first being opened, OR
  1564. // - after a search has been performed, OR
  1565. // - 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)
  1566. keepActive = thisIsActive || selected && !this.multiple && !activeIndexIsSet;
  1567. if (!liIndex) liIndex = this.selectpicker.main.map.newIndex[index];
  1568. if (!li) li = this.selectpicker.main.elements[liIndex];
  1569. a = li.firstChild;
  1570. if (selected) {
  1571. this.selectedIndex = index;
  1572. }
  1573. li.classList.toggle('selected', selected);
  1574. li.classList.toggle('active', keepActive);
  1575. if (keepActive) {
  1576. this.selectpicker.view.currentActive = li;
  1577. this.activeIndex = index;
  1578. }
  1579. if (a) {
  1580. a.classList.toggle('selected', selected);
  1581. a.classList.toggle('active', keepActive);
  1582. a.setAttribute('aria-selected', selected);
  1583. }
  1584. if (!keepActive) {
  1585. if (!activeIndexIsSet && selected && this.prevActiveIndex !== undefined) {
  1586. prevActiveIndex = this.selectpicker.main.map.newIndex[this.prevActiveIndex];
  1587. prevActive = this.selectpicker.main.elements[prevActiveIndex];
  1588. prevActive.classList.toggle('selected', selected);
  1589. prevActive.classList.remove('active');
  1590. if (prevActive.firstChild) {
  1591. prevActive.firstChild.classList.toggle('selected', selected);
  1592. prevActive.firstChild.classList.remove('active');
  1593. }
  1594. }
  1595. }
  1596. },
  1597. /**
  1598. * @param {number} index - the index of the option that is being disabled
  1599. * @param {boolean} disabled - true if the option is being disabled, false if being enabled
  1600. */
  1601. setDisabled: function (index, disabled, liIndex, li) {
  1602. var a;
  1603. if (!liIndex) liIndex = this.selectpicker.main.map.newIndex[index];
  1604. if (!li) li = this.selectpicker.main.elements[liIndex];
  1605. a = li.firstChild;
  1606. li.classList.toggle(classNames.DISABLED, disabled);
  1607. if (a) {
  1608. if (version.major === '4') a.classList.toggle(classNames.DISABLED, disabled);
  1609. a.setAttribute('aria-disabled', disabled);
  1610. if (disabled) {
  1611. a.setAttribute('tabindex', -1);
  1612. } else {
  1613. a.setAttribute('tabindex', 0);
  1614. }
  1615. }
  1616. },
  1617. isDisabled: function () {
  1618. return this.$element[0].disabled;
  1619. },
  1620. checkDisabled: function () {
  1621. var that = this;
  1622. if (this.isDisabled()) {
  1623. this.$newElement.addClass(classNames.DISABLED);
  1624. this.$button.addClass(classNames.DISABLED).attr('tabindex', -1).attr('aria-disabled', true);
  1625. } else {
  1626. if (this.$button.hasClass(classNames.DISABLED)) {
  1627. this.$newElement.removeClass(classNames.DISABLED);
  1628. this.$button.removeClass(classNames.DISABLED).attr('aria-disabled', false);
  1629. }
  1630. if (this.$button.attr('tabindex') == -1 && !this.$element.data('tabindex')) {
  1631. this.$button.removeAttr('tabindex');
  1632. }
  1633. }
  1634. this.$button.click(function () {
  1635. return !that.isDisabled();
  1636. });
  1637. },
  1638. togglePlaceholder: function () {
  1639. // much faster than calling $.val()
  1640. var element = this.$element[0],
  1641. selectedIndex = element.selectedIndex,
  1642. nothingSelected = selectedIndex === -1;
  1643. if (!nothingSelected && !element.options[selectedIndex].value) nothingSelected = true;
  1644. this.$button.toggleClass('bs-placeholder', nothingSelected);
  1645. },
  1646. tabIndex: function () {
  1647. if (this.$element.data('tabindex') !== this.$element.attr('tabindex') &&
  1648. (this.$element.attr('tabindex') !== -98 && this.$element.attr('tabindex') !== '-98')) {
  1649. this.$element.data('tabindex', this.$element.attr('tabindex'));
  1650. this.$button.attr('tabindex', this.$element.data('tabindex'));
  1651. }
  1652. this.$element.attr('tabindex', -98);
  1653. },
  1654. clickListener: function () {
  1655. var that = this,
  1656. $document = $(document);
  1657. $document.data('spaceSelect', false);
  1658. this.$button.on('keyup', function (e) {
  1659. if (/(32)/.test(e.keyCode.toString(10)) && $document.data('spaceSelect')) {
  1660. e.preventDefault();
  1661. $document.data('spaceSelect', false);
  1662. }
  1663. });
  1664. this.$newElement.on('show.bs.dropdown', function() {
  1665. if (version.major > 3 && !that.dropdown) {
  1666. that.dropdown = that.$button.data('bs.dropdown');
  1667. that.dropdown._menu = that.$menu[0];
  1668. }
  1669. });
  1670. this.$button.on('click.bs.dropdown.data-api', function () {
  1671. if (!that.$newElement.hasClass(classNames.SHOW)) {
  1672. that.setSize();
  1673. }
  1674. });
  1675. function setFocus () {
  1676. if (that.options.liveSearch) {
  1677. that.$searchbox.focus();
  1678. } else {
  1679. that.$menuInner.focus();
  1680. }
  1681. }
  1682. function checkPopperExists () {
  1683. if (that.dropdown && that.dropdown._popper && that.dropdown._popper.state.isCreated) {
  1684. setFocus();
  1685. } else {
  1686. requestAnimationFrame(checkPopperExists);
  1687. }
  1688. }
  1689. this.$element.on('shown.bs.select', function () {
  1690. if (that.$menuInner[0].scrollTop !== that.selectpicker.view.scrollTop) {
  1691. that.$menuInner[0].scrollTop = that.selectpicker.view.scrollTop;
  1692. }
  1693. if (version.major > 3) {
  1694. requestAnimationFrame(checkPopperExists);
  1695. } else {
  1696. setFocus();
  1697. }
  1698. });
  1699. this.$menuInner.on('click', 'li a', function (e, retainActive) {
  1700. var $this = $(this),
  1701. position0 = that.isVirtual() ? that.selectpicker.view.position0 : 0,
  1702. clickedIndex = that.selectpicker.current.map.originalIndex[$this.parent().index() + position0],
  1703. prevValue = getSelectValues(that.$element[0]),
  1704. prevIndex = that.$element.prop('selectedIndex'),
  1705. triggerChange = true;
  1706. // Don't close on multi choice menu
  1707. if (that.multiple && that.options.maxOptions !== 1) {
  1708. e.stopPropagation();
  1709. }
  1710. e.preventDefault();
  1711. //Don't run if we have been disabled
  1712. if (!that.isDisabled() && !$this.parent().hasClass(classNames.DISABLED)) {
  1713. var $options = that.$element.find('option'),
  1714. $option = $options.eq(clickedIndex),
  1715. state = $option.prop('selected'),
  1716. $optgroup = $option.parent('optgroup'),
  1717. $optgroupOptions = $optgroup.find('option'),
  1718. maxOptions = that.options.maxOptions,
  1719. maxOptionsGrp = $optgroup.data('maxOptions') || false;
  1720. if (clickedIndex === that.activeIndex) retainActive = true;
  1721. if (!retainActive) {
  1722. that.prevActiveIndex = that.activeIndex;
  1723. that.activeIndex = undefined;
  1724. }
  1725. if (!that.multiple) { // Deselect all others if not multi select box
  1726. $options.prop('selected', false);
  1727. $option.prop('selected', true);
  1728. that.setSelected(clickedIndex, true);
  1729. } else { // Toggle the one we have chosen if we are multi select.
  1730. $option.prop('selected', !state);
  1731. that.setSelected(clickedIndex, !state);
  1732. $this.blur();
  1733. if (maxOptions !== false || maxOptionsGrp !== false) {
  1734. var maxReached = maxOptions < $options.filter(':selected').length,
  1735. maxReachedGrp = maxOptionsGrp < $optgroup.find('option:selected').length;
  1736. if ((maxOptions && maxReached) || (maxOptionsGrp && maxReachedGrp)) {
  1737. if (maxOptions && maxOptions == 1) {
  1738. $options.prop('selected', false);
  1739. $option.prop('selected', true);
  1740. for (var i = 0; i < $options.length; i++) {
  1741. that.setSelected(i, false);
  1742. }
  1743. that.setSelected(clickedIndex, true);
  1744. } else if (maxOptionsGrp && maxOptionsGrp == 1) {
  1745. $optgroup.find('option:selected').prop('selected', false);
  1746. $option.prop('selected', true);
  1747. for (var i = 0; i < $optgroupOptions.length; i++) {
  1748. var option = $optgroupOptions[i];
  1749. that.setSelected($options.index(option), false);
  1750. }
  1751. that.setSelected(clickedIndex, true);
  1752. } else {
  1753. var maxOptionsText = typeof that.options.maxOptionsText === 'string' ? [that.options.maxOptionsText, that.options.maxOptionsText] : that.options.maxOptionsText,
  1754. maxOptionsArr = typeof maxOptionsText === 'function' ? maxOptionsText(maxOptions, maxOptionsGrp) : maxOptionsText,
  1755. maxTxt = maxOptionsArr[0].replace('{n}', maxOptions),
  1756. maxTxtGrp = maxOptionsArr[1].replace('{n}', maxOptionsGrp),
  1757. $notify = $('<div class="notify"></div>');
  1758. // If {var} is set in array, replace it
  1759. /** @deprecated */
  1760. if (maxOptionsArr[2]) {
  1761. maxTxt = maxTxt.replace('{var}', maxOptionsArr[2][maxOptions > 1 ? 0 : 1]);
  1762. maxTxtGrp = maxTxtGrp.replace('{var}', maxOptionsArr[2][maxOptionsGrp > 1 ? 0 : 1]);
  1763. }
  1764. $option.prop('selected', false);
  1765. that.$menu.append($notify);
  1766. if (maxOptions && maxReached) {
  1767. $notify.append($('<div>' + maxTxt + '</div>'));
  1768. triggerChange = false;
  1769. that.$element.trigger('maxReached.bs.select');
  1770. }
  1771. if (maxOptionsGrp && maxReachedGrp) {
  1772. $notify.append($('<div>' + maxTxtGrp + '</div>'));
  1773. triggerChange = false;
  1774. that.$element.trigger('maxReachedGrp.bs.select');
  1775. }
  1776. setTimeout(function () {
  1777. that.setSelected(clickedIndex, false);
  1778. }, 10);
  1779. $notify.delay(750).fadeOut(300, function () {
  1780. $(this).remove();
  1781. });
  1782. }
  1783. }
  1784. }
  1785. }
  1786. if (!that.multiple || (that.multiple && that.options.maxOptions === 1)) {
  1787. that.$button.focus();
  1788. } else if (that.options.liveSearch) {
  1789. that.$searchbox.focus();
  1790. }
  1791. // Trigger select 'change'
  1792. if (triggerChange) {
  1793. if ((prevValue != getSelectValues(that.$element[0]) && that.multiple) || (prevIndex != that.$element.prop('selectedIndex') && !that.multiple)) {
  1794. // $option.prop('selected') is current option state (selected/unselected). prevValue is the value of the select prior to being changed.
  1795. changed_arguments = [clickedIndex, $option.prop('selected'), prevValue];
  1796. that.$element
  1797. .triggerNative('change');
  1798. }
  1799. }
  1800. }
  1801. });
  1802. this.$menu.on('click', 'li.' + classNames.DISABLED + ' a, .' + classNames.POPOVERHEADER + ', .' + classNames.POPOVERHEADER + ' :not(.close)', function (e) {
  1803. if (e.currentTarget == this) {
  1804. e.preventDefault();
  1805. e.stopPropagation();
  1806. if (that.options.liveSearch && !$(e.target).hasClass('close')) {
  1807. that.$searchbox.focus();
  1808. } else {
  1809. that.$button.focus();
  1810. }
  1811. }
  1812. });
  1813. this.$menuInner.on('click', '.divider, .dropdown-header', function (e) {
  1814. e.preventDefault();
  1815. e.stopPropagation();
  1816. if (that.options.liveSearch) {
  1817. that.$searchbox.focus();
  1818. } else {
  1819. that.$button.focus();
  1820. }
  1821. });
  1822. this.$menu.on('click', '.' + classNames.POPOVERHEADER + ' .close', function () {
  1823. that.$button.click();
  1824. });
  1825. this.$searchbox.on('click', function (e) {
  1826. e.stopPropagation();
  1827. });
  1828. this.$menu.on('click', '.actions-btn', function (e) {
  1829. if (that.options.liveSearch) {
  1830. that.$searchbox.focus();
  1831. } else {
  1832. that.$button.focus();
  1833. }
  1834. e.preventDefault();
  1835. e.stopPropagation();
  1836. if ($(this).hasClass('bs-select-all')) {
  1837. that.selectAll();
  1838. } else {
  1839. that.deselectAll();
  1840. }
  1841. });
  1842. this.$element.on({
  1843. 'change': function () {
  1844. that.render();
  1845. that.$element.trigger('changed.bs.select', changed_arguments);
  1846. changed_arguments = null;
  1847. },
  1848. 'focus': function () {
  1849. that.$button.focus();
  1850. }
  1851. });
  1852. },
  1853. liveSearchListener: function () {
  1854. var that = this,
  1855. no_results = document.createElement('li');
  1856. this.$button.on('click.bs.dropdown.data-api', function () {
  1857. if (!!that.$searchbox.val()) {
  1858. that.$searchbox.val('');
  1859. }
  1860. });
  1861. this.$searchbox.on('click.bs.dropdown.data-api focus.bs.dropdown.data-api touchend.bs.dropdown.data-api', function (e) {
  1862. e.stopPropagation();
  1863. });
  1864. this.$searchbox.on('input propertychange', function () {
  1865. var searchValue = that.$searchbox.val();
  1866. that.selectpicker.search.map.newIndex = {};
  1867. that.selectpicker.search.map.originalIndex = {};
  1868. that.selectpicker.search.elements = [];
  1869. that.selectpicker.search.data = [];
  1870. if (searchValue) {
  1871. var i,
  1872. searchMatch = [],
  1873. q = searchValue.toUpperCase(),
  1874. cache = {},
  1875. cacheArr = [],
  1876. searchStyle = that._searchStyle(),
  1877. normalizeSearch = that.options.liveSearchNormalize;
  1878. that._$lisSelected = that.$menuInner.find('.selected');
  1879. for (var i = 0; i < that.selectpicker.main.data.length; i++) {
  1880. var li = that.selectpicker.main.data[i];
  1881. if (!cache[i]) {
  1882. cache[i] = stringSearch(li, q, searchStyle, normalizeSearch);
  1883. }
  1884. if (cache[i] && li.headerIndex !== undefined && cacheArr.indexOf(li.headerIndex) === -1) {
  1885. if (li.headerIndex > 0) {
  1886. cache[li.headerIndex - 1] = true;
  1887. cacheArr.push(li.headerIndex - 1);
  1888. }
  1889. cache[li.headerIndex] = true;
  1890. cacheArr.push(li.headerIndex);
  1891. cache[li.lastIndex + 1] = true;
  1892. }
  1893. if (cache[i] && li.type !== 'optgroup-label') cacheArr.push(i);
  1894. }
  1895. for (var i = 0, cacheLen = cacheArr.length; i < cacheLen; i++) {
  1896. var index = cacheArr[i],
  1897. prevIndex = cacheArr[i - 1],
  1898. li = that.selectpicker.main.data[index],
  1899. liPrev = that.selectpicker.main.data[prevIndex];
  1900. if ( li.type !== 'divider' || ( li.type === 'divider' && liPrev && liPrev.type !== 'divider' && cacheLen - 1 !== i ) ) {
  1901. that.selectpicker.search.data.push(li);
  1902. searchMatch.push(that.selectpicker.main.elements[index]);
  1903. if (li.hasOwnProperty('originalIndex')) {
  1904. that.selectpicker.search.map.newIndex[li.originalIndex] = searchMatch.length - 1;
  1905. that.selectpicker.search.map.originalIndex[searchMatch.length - 1] = li.originalIndex;
  1906. }
  1907. }
  1908. }
  1909. that.activeIndex = undefined;
  1910. that.noScroll = true;
  1911. that.$menuInner.scrollTop(0);
  1912. that.selectpicker.search.elements = searchMatch;
  1913. that.createView(true);
  1914. if (!searchMatch.length) {
  1915. no_results.className = 'no-results';
  1916. no_results.innerHTML = that.options.noneResultsText.replace('{0}', '"' + htmlEscape(searchValue) + '"');
  1917. that.$menuInner[0].firstChild.appendChild(no_results);
  1918. }
  1919. } else {
  1920. that.$menuInner.scrollTop(0);
  1921. that.createView(false);
  1922. }
  1923. });
  1924. },
  1925. _searchStyle: function () {
  1926. return this.options.liveSearchStyle || 'contains';
  1927. },
  1928. val: function (value) {
  1929. if (typeof value !== 'undefined') {
  1930. this.$element
  1931. .val(value)
  1932. .triggerNative('change');
  1933. return this.$element;
  1934. } else {
  1935. return this.$element.val();
  1936. }
  1937. },
  1938. changeAll: function (status) {
  1939. if (!this.multiple) return;
  1940. if (typeof status === 'undefined') status = true;
  1941. var $selectOptions = this.$element.find('option'),
  1942. previousSelected = 0,
  1943. currentSelected = 0,
  1944. prevValue = getSelectValues(this.$element[0]);
  1945. this.$element.addClass('bs-select-hidden');
  1946. for (var i = 0; i < this.selectpicker.current.elements.length; i++) {
  1947. var liData = this.selectpicker.current.data[i],
  1948. index = this.selectpicker.current.map.originalIndex[i], // faster than $(li).data('originalIndex')
  1949. option = $selectOptions[index];
  1950. if (option && !option.disabled && liData.type !== 'divider') {
  1951. if (option.selected) previousSelected++;
  1952. option.selected = status;
  1953. if (option.selected) currentSelected++;
  1954. }
  1955. }
  1956. this.$element.removeClass('bs-select-hidden');
  1957. if (previousSelected === currentSelected) return;
  1958. this.setOptionStatus();
  1959. this.togglePlaceholder();
  1960. changed_arguments = [null, null, prevValue];
  1961. this.$element
  1962. .triggerNative('change');
  1963. },
  1964. selectAll: function () {
  1965. return this.changeAll(true);
  1966. },
  1967. deselectAll: function () {
  1968. return this.changeAll(false);
  1969. },
  1970. toggle: function (e) {
  1971. e = e || window.event;
  1972. if (e) e.stopPropagation();
  1973. this.$button.trigger('click.bs.dropdown.data-api');
  1974. },
  1975. keydown: function (e) {
  1976. var $this = $(this),
  1977. isToggle = $this.hasClass('dropdown-toggle'),
  1978. $parent = isToggle ? $this.closest('.dropdown') : $this.closest(Selector.MENU),
  1979. that = $parent.data('this'),
  1980. $items = that.findLis(),
  1981. index,
  1982. isActive,
  1983. liActive,
  1984. activeLi,
  1985. offset,
  1986. updateScroll = false,
  1987. downOnTab = e.which === keyCodes.TAB && !isToggle && !that.options.selectOnTab,
  1988. isArrowKey = REGEXP_ARROW.test(e.which) || downOnTab,
  1989. scrollTop = that.$menuInner[0].scrollTop,
  1990. isVirtual = that.isVirtual(),
  1991. position0 = isVirtual === true ? that.selectpicker.view.position0 : 0;
  1992. isActive = that.$newElement.hasClass(classNames.SHOW);
  1993. if (
  1994. !isActive &&
  1995. (
  1996. isArrowKey ||
  1997. e.which >= 48 && e.which <= 57 ||
  1998. e.which >= 96 && e.which <= 105 ||
  1999. e.which >= 65 && e.which <= 90
  2000. )
  2001. ) {
  2002. that.$button.trigger('click.bs.dropdown.data-api');
  2003. }
  2004. if (e.which === keyCodes.ESCAPE && isActive) {
  2005. e.preventDefault();
  2006. that.$button.trigger('click.bs.dropdown.data-api').focus();
  2007. }
  2008. if (isArrowKey) { // if up or down
  2009. if (!$items.length) return;
  2010. // $items.index/.filter is too slow with a large list and no virtual scroll
  2011. index = isVirtual === true ? $items.index($items.filter('.active')) : that.selectpicker.current.map.newIndex[that.activeIndex];
  2012. if (index === undefined) index = -1;
  2013. if (index !== -1) {
  2014. liActive = that.selectpicker.current.elements[index + position0];
  2015. liActive.classList.remove('active');
  2016. if (liActive.firstChild) liActive.firstChild.classList.remove('active');
  2017. }
  2018. if (e.which === keyCodes.ARROW_UP) { // up
  2019. if (index !== -1) index--;
  2020. if (index + position0 < 0) index += $items.length;
  2021. if (!that.selectpicker.view.canHighlight[index + position0]) {
  2022. index = that.selectpicker.view.canHighlight.slice(0, index + position0).lastIndexOf(true) - position0;
  2023. if (index === -1) index = $items.length - 1;
  2024. }
  2025. } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down
  2026. index++;
  2027. if (index + position0 >= that.selectpicker.view.canHighlight.length) index = 0;
  2028. if (!that.selectpicker.view.canHighlight[index + position0]) {
  2029. index = index + 1 + that.selectpicker.view.canHighlight.slice(index + position0 + 1).indexOf(true);
  2030. }
  2031. }
  2032. e.preventDefault();
  2033. var liActiveIndex = position0 + index;
  2034. if (e.which === keyCodes.ARROW_UP) { // up
  2035. // scroll to bottom and highlight last option
  2036. if (position0 === 0 && index === $items.length - 1) {
  2037. that.$menuInner[0].scrollTop = that.$menuInner[0].scrollHeight;
  2038. liActiveIndex = that.selectpicker.current.elements.length - 1;
  2039. } else {
  2040. activeLi = that.selectpicker.current.data[liActiveIndex];
  2041. offset = activeLi.position - activeLi.height;
  2042. updateScroll = offset < scrollTop;
  2043. }
  2044. } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down
  2045. // scroll to top and highlight first option
  2046. if (index === 0) {
  2047. that.$menuInner[0].scrollTop = 0;
  2048. liActiveIndex = 0;
  2049. } else {
  2050. activeLi = that.selectpicker.current.data[liActiveIndex];
  2051. offset = activeLi.position - that.sizeInfo.menuInnerHeight;
  2052. updateScroll = offset > scrollTop;
  2053. }
  2054. }
  2055. liActive = that.selectpicker.current.elements[liActiveIndex];
  2056. if (liActive) {
  2057. liActive.classList.add('active');
  2058. if (liActive.firstChild) liActive.firstChild.classList.add('active');
  2059. }
  2060. that.activeIndex = that.selectpicker.current.map.originalIndex[liActiveIndex];
  2061. that.selectpicker.view.currentActive = liActive;
  2062. if (updateScroll) that.$menuInner[0].scrollTop = offset;
  2063. if (that.options.liveSearch) {
  2064. that.$searchbox.focus();
  2065. } else {
  2066. $this.focus();
  2067. }
  2068. } else if (
  2069. !$this.is('input') &&
  2070. !REGEXP_TAB_OR_ESCAPE.test(e.which) ||
  2071. (e.which === keyCodes.SPACE && that.selectpicker.keydown.keyHistory)
  2072. ) {
  2073. var searchMatch,
  2074. matches = [],
  2075. keyHistory;
  2076. e.preventDefault();
  2077. that.selectpicker.keydown.keyHistory += keyCodeMap[e.which];
  2078. if (that.selectpicker.keydown.resetKeyHistory.cancel) clearTimeout(that.selectpicker.keydown.resetKeyHistory.cancel);
  2079. that.selectpicker.keydown.resetKeyHistory.cancel = that.selectpicker.keydown.resetKeyHistory.start();
  2080. keyHistory = that.selectpicker.keydown.keyHistory;
  2081. // if all letters are the same, set keyHistory to just the first character when searching
  2082. if (/^(.)\1+$/.test(keyHistory)) {
  2083. keyHistory = keyHistory.charAt(0);
  2084. }
  2085. // find matches
  2086. for (var i = 0; i < that.selectpicker.current.data.length; i++) {
  2087. var li = that.selectpicker.current.data[i],
  2088. hasMatch;
  2089. hasMatch = stringSearch(li, keyHistory, 'startsWith', true);
  2090. if (hasMatch && that.selectpicker.view.canHighlight[i]) {
  2091. li.index = i;
  2092. matches.push(li.originalIndex);
  2093. }
  2094. }
  2095. if (matches.length) {
  2096. var matchIndex = 0;
  2097. $items.removeClass('active').find('a').removeClass('active');
  2098. // either only one key has been pressed or they are all the same key
  2099. if (keyHistory.length === 1) {
  2100. matchIndex = matches.indexOf(that.activeIndex);
  2101. if (matchIndex === -1 || matchIndex === matches.length - 1) {
  2102. matchIndex = 0;
  2103. } else {
  2104. matchIndex++;
  2105. }
  2106. }
  2107. searchMatch = that.selectpicker.current.map.newIndex[matches[matchIndex]];
  2108. activeLi = that.selectpicker.current.data[searchMatch];
  2109. if (scrollTop - activeLi.position > 0) {
  2110. offset = activeLi.position - activeLi.height;
  2111. updateScroll = true;
  2112. } else {
  2113. offset = activeLi.position - that.sizeInfo.menuInnerHeight;
  2114. // if the option is already visible at the current scroll position, just keep it the same
  2115. updateScroll = activeLi.position > scrollTop + that.sizeInfo.menuInnerHeight;
  2116. }
  2117. liActive = that.selectpicker.current.elements[searchMatch];
  2118. liActive.classList.add('active');
  2119. if (liActive.firstChild) liActive.firstChild.classList.add('active');
  2120. that.activeIndex = matches[matchIndex];
  2121. liActive.firstChild.focus();
  2122. if (updateScroll) that.$menuInner[0].scrollTop = offset;
  2123. $this.focus();
  2124. }
  2125. }
  2126. // Select focused option if "Enter", "Spacebar" or "Tab" (when selectOnTab is true) are pressed inside the menu.
  2127. if (
  2128. isActive &&
  2129. (
  2130. (e.which === keyCodes.SPACE && !that.selectpicker.keydown.keyHistory) ||
  2131. e.which === keyCodes.ENTER ||
  2132. (e.which === keyCodes.TAB && that.options.selectOnTab)
  2133. )
  2134. ) {
  2135. if (e.which !== keyCodes.SPACE) e.preventDefault();
  2136. if (!that.options.liveSearch || e.which !== keyCodes.SPACE) {
  2137. that.$menuInner.find('.active a').trigger('click', true); // retain active class
  2138. $this.focus();
  2139. if (!that.options.liveSearch) {
  2140. // Prevent screen from scrolling if the user hits the spacebar
  2141. e.preventDefault();
  2142. // Fixes spacebar selection of dropdown items in FF & IE
  2143. $(document).data('spaceSelect', true);
  2144. }
  2145. }
  2146. }
  2147. },
  2148. mobile: function () {
  2149. this.$element.addClass('mobile-device');
  2150. },
  2151. refresh: function () {
  2152. // update options if data attributes have been changed
  2153. var config = $.extend({}, this.options, this.$element.data());
  2154. this.options = config;
  2155. this.selectpicker.main.map.newIndex = {};
  2156. this.selectpicker.main.map.originalIndex = {};
  2157. this.createLi();
  2158. this.checkDisabled();
  2159. this.render();
  2160. this.setStyle();
  2161. this.setWidth();
  2162. this.setSize(true);
  2163. this.$element.trigger('refreshed.bs.select');
  2164. },
  2165. hide: function () {
  2166. this.$newElement.hide();
  2167. },
  2168. show: function () {
  2169. this.$newElement.show();
  2170. },
  2171. remove: function () {
  2172. this.$newElement.remove();
  2173. this.$element.remove();
  2174. },
  2175. destroy: function () {
  2176. this.$newElement.before(this.$element).remove();
  2177. if (this.$bsContainer) {
  2178. this.$bsContainer.remove();
  2179. } else {
  2180. this.$menu.remove();
  2181. }
  2182. this.$element
  2183. .off('.bs.select')
  2184. .removeData('selectpicker')
  2185. .removeClass('bs-select-hidden selectpicker');
  2186. }
  2187. };
  2188. // SELECTPICKER PLUGIN DEFINITION
  2189. // ==============================
  2190. function Plugin(option) {
  2191. // get the args of the outer function..
  2192. var args = arguments;
  2193. // The arguments of the function are explicitly re-defined from the argument list, because the shift causes them
  2194. // to get lost/corrupted in android 2.3 and IE9 #715 #775
  2195. var _option = option;
  2196. [].shift.apply(args);
  2197. // if the version was not set successfully
  2198. if (!version.success) {
  2199. // try to retreive it again
  2200. try {
  2201. version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.');
  2202. }
  2203. // fall back to use BootstrapVersion
  2204. catch(err) {
  2205. version.full = Selectpicker.BootstrapVersion.split(' ')[0].split('.');
  2206. }
  2207. version.major = version.full[0];
  2208. version.success = true;
  2209. if (version.major === '4') {
  2210. classNames.DIVIDER = 'dropdown-divider';
  2211. classNames.SHOW = 'show';
  2212. classNames.BUTTONCLASS = 'btn-light';
  2213. Selectpicker.DEFAULTS.style = classNames.BUTTONCLASS = 'btn-light';
  2214. classNames.POPOVERHEADER = 'popover-header';
  2215. }
  2216. }
  2217. var value;
  2218. var chain = this.each(function () {
  2219. var $this = $(this);
  2220. if ($this.is('select')) {
  2221. var data = $this.data('selectpicker'),
  2222. options = typeof _option == 'object' && _option;
  2223. if (!data) {
  2224. var config = $.extend({}, Selectpicker.DEFAULTS, $.fn.selectpicker.defaults || {}, $this.data(), options);
  2225. config.template = $.extend({}, Selectpicker.DEFAULTS.template, ($.fn.selectpicker.defaults ? $.fn.selectpicker.defaults.template : {}), $this.data().template, options.template);
  2226. $this.data('selectpicker', (data = new Selectpicker(this, config)));
  2227. } else if (options) {
  2228. for (var i in options) {
  2229. if (options.hasOwnProperty(i)) {
  2230. data.options[i] = options[i];
  2231. }
  2232. }
  2233. }
  2234. if (typeof _option == 'string') {
  2235. if (data[_option] instanceof Function) {
  2236. value = data[_option].apply(data, args);
  2237. } else {
  2238. value = data.options[_option];
  2239. }
  2240. }
  2241. }
  2242. });
  2243. if (typeof value !== 'undefined') {
  2244. //noinspection JSUnusedAssignment
  2245. return value;
  2246. } else {
  2247. return chain;
  2248. }
  2249. }
  2250. var old = $.fn.selectpicker;
  2251. $.fn.selectpicker = Plugin;
  2252. $.fn.selectpicker.Constructor = Selectpicker;
  2253. // SELECTPICKER NO CONFLICT
  2254. // ========================
  2255. $.fn.selectpicker.noConflict = function () {
  2256. $.fn.selectpicker = old;
  2257. return this;
  2258. };
  2259. $(document)
  2260. .off('keydown.bs.dropdown.data-api')
  2261. .on('keydown.bs.select', '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bs-searchbox input', Selectpicker.prototype.keydown)
  2262. .on('focusin.modal', '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bs-searchbox input', function (e) {
  2263. e.stopPropagation();
  2264. });
  2265. // SELECTPICKER DATA-API
  2266. // =====================
  2267. $(window).on('load.bs.select.data-api', function () {
  2268. $('.selectpicker').each(function () {
  2269. var $selectpicker = $(this);
  2270. Plugin.call($selectpicker, $selectpicker.data());
  2271. })
  2272. });
  2273. })(jQuery);
  2274. }));