jquery.select-bootstrap.js 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948
  1. /*!
  2. * Bootstrap-select v1.12.2 (http://silviomoreto.github.io/bootstrap-select)
  3. *
  4. * Copyright 2013-2017 bootstrap-select
  5. * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
  6. */
  7. /*
  8. Creative Tim Modifications
  9. Line: 379-380 - we changed glyphicons with material-icons.
  10. Line: 593 - we put tickIcon inside of span tag.
  11. */
  12. (function(root, factory) {
  13. if (typeof define === 'function' && define.amd) {
  14. // AMD. Register as an anonymous module unless amdModuleId is set
  15. define(["jquery"], function(a0) {
  16. return (factory(a0));
  17. });
  18. } else if (typeof module === 'object' && module.exports) {
  19. // Node. Does not work with strict CommonJS, but
  20. // only CommonJS-like environments that support module.exports,
  21. // like Node.
  22. module.exports = factory(require("jquery"));
  23. } else {
  24. factory(root["jQuery"]);
  25. }
  26. }(this, function(jQuery) {
  27. (function($) {
  28. 'use strict';
  29. //<editor-fold desc="Shims">
  30. if (!String.prototype.includes) {
  31. (function() {
  32. 'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
  33. var toString = {}.toString;
  34. var defineProperty = (function() {
  35. // IE 8 only supports `Object.defineProperty` on DOM elements
  36. try {
  37. var object = {};
  38. var $defineProperty = Object.defineProperty;
  39. var result = $defineProperty(object, object, object) && $defineProperty;
  40. } catch (error) {}
  41. return result;
  42. }());
  43. var indexOf = ''.indexOf;
  44. var includes = function(search) {
  45. if (this == null) {
  46. throw new TypeError();
  47. }
  48. var string = String(this);
  49. if (search && toString.call(search) == '[object RegExp]') {
  50. throw new TypeError();
  51. }
  52. var stringLength = string.length;
  53. var searchString = String(search);
  54. var searchLength = searchString.length;
  55. var position = arguments.length > 1 ? arguments[1] : undefined;
  56. // `ToInteger`
  57. var pos = position ? Number(position) : 0;
  58. if (pos != pos) { // better `isNaN`
  59. pos = 0;
  60. }
  61. var start = Math.min(Math.max(pos, 0), stringLength);
  62. // Avoid the `indexOf` call if no match is possible
  63. if (searchLength + start > stringLength) {
  64. return false;
  65. }
  66. return indexOf.call(string, searchString, pos) != -1;
  67. };
  68. if (defineProperty) {
  69. defineProperty(String.prototype, 'includes', {
  70. 'value': includes,
  71. 'configurable': true,
  72. 'writable': true
  73. });
  74. } else {
  75. String.prototype.includes = includes;
  76. }
  77. }());
  78. }
  79. if (!String.prototype.startsWith) {
  80. (function() {
  81. 'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
  82. var defineProperty = (function() {
  83. // IE 8 only supports `Object.defineProperty` on DOM elements
  84. try {
  85. var object = {};
  86. var $defineProperty = Object.defineProperty;
  87. var result = $defineProperty(object, object, object) && $defineProperty;
  88. } catch (error) {}
  89. return result;
  90. }());
  91. var toString = {}.toString;
  92. var startsWith = function(search) {
  93. if (this == null) {
  94. throw new TypeError();
  95. }
  96. var string = String(this);
  97. if (search && toString.call(search) == '[object RegExp]') {
  98. throw new TypeError();
  99. }
  100. var stringLength = string.length;
  101. var searchString = String(search);
  102. var searchLength = searchString.length;
  103. var position = arguments.length > 1 ? arguments[1] : undefined;
  104. // `ToInteger`
  105. var pos = position ? Number(position) : 0;
  106. if (pos != pos) { // better `isNaN`
  107. pos = 0;
  108. }
  109. var start = Math.min(Math.max(pos, 0), stringLength);
  110. // Avoid the `indexOf` call if no match is possible
  111. if (searchLength + start > stringLength) {
  112. return false;
  113. }
  114. var index = -1;
  115. while (++index < searchLength) {
  116. if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {
  117. return false;
  118. }
  119. }
  120. return true;
  121. };
  122. if (defineProperty) {
  123. defineProperty(String.prototype, 'startsWith', {
  124. 'value': startsWith,
  125. 'configurable': true,
  126. 'writable': true
  127. });
  128. } else {
  129. String.prototype.startsWith = startsWith;
  130. }
  131. }());
  132. }
  133. if (!Object.keys) {
  134. Object.keys = function(
  135. o, // object
  136. k, // key
  137. r // result array
  138. ) {
  139. // initialize object and result
  140. r = [];
  141. // iterate over object keys
  142. for (k in o)
  143. // fill result array with non-prototypical keys
  144. r.hasOwnProperty.call(o, k) && r.push(k);
  145. // return result
  146. return r;
  147. };
  148. }
  149. // set data-selected on select element if the value has been programmatically selected
  150. // prior to initialization of bootstrap-select
  151. // * consider removing or replacing an alternative method *
  152. var valHooks = {
  153. useDefault: false,
  154. _set: $.valHooks.select.set
  155. };
  156. $.valHooks.select.set = function(elem, value) {
  157. if (value && !valHooks.useDefault) $(elem).data('selected', true);
  158. return valHooks._set.apply(this, arguments);
  159. };
  160. var changed_arguments = null;
  161. $.fn.triggerNative = function(eventName) {
  162. var el = this[0],
  163. event;
  164. if (el.dispatchEvent) { // for modern browsers & IE9+
  165. if (typeof Event === 'function') {
  166. // For modern browsers
  167. event = new Event(eventName, {
  168. bubbles: true
  169. });
  170. } else {
  171. // For IE since it doesn't support Event constructor
  172. event = document.createEvent('Event');
  173. event.initEvent(eventName, true, false);
  174. }
  175. el.dispatchEvent(event);
  176. } else if (el.fireEvent) { // for IE8
  177. event = document.createEventObject();
  178. event.eventType = eventName;
  179. el.fireEvent('on' + eventName, event);
  180. } else {
  181. // fall back to jQuery.trigger
  182. this.trigger(eventName);
  183. }
  184. };
  185. //</editor-fold>
  186. // Case insensitive contains search
  187. $.expr.pseudos.icontains = function(obj, index, meta) {
  188. var $obj = $(obj);
  189. var haystack = ($obj.data('tokens') || $obj.text()).toString().toUpperCase();
  190. return haystack.includes(meta[3].toUpperCase());
  191. };
  192. // Case insensitive begins search
  193. $.expr.pseudos.ibegins = function(obj, index, meta) {
  194. var $obj = $(obj);
  195. var haystack = ($obj.data('tokens') || $obj.text()).toString().toUpperCase();
  196. return haystack.startsWith(meta[3].toUpperCase());
  197. };
  198. // Case and accent insensitive contains search
  199. $.expr.pseudos.aicontains = function(obj, index, meta) {
  200. var $obj = $(obj);
  201. var haystack = ($obj.data('tokens') || $obj.data('normalizedText') || $obj.text()).toString().toUpperCase();
  202. return haystack.includes(meta[3].toUpperCase());
  203. };
  204. // Case and accent insensitive begins search
  205. $.expr.pseudos.aibegins = function(obj, index, meta) {
  206. var $obj = $(obj);
  207. var haystack = ($obj.data('tokens') || $obj.data('normalizedText') || $obj.text()).toString().toUpperCase();
  208. return haystack.startsWith(meta[3].toUpperCase());
  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,
  219. ch: "A"
  220. },
  221. {
  222. re: /[\xE0-\xE6]/g,
  223. ch: "a"
  224. },
  225. {
  226. re: /[\xC8-\xCB]/g,
  227. ch: "E"
  228. },
  229. {
  230. re: /[\xE8-\xEB]/g,
  231. ch: "e"
  232. },
  233. {
  234. re: /[\xCC-\xCF]/g,
  235. ch: "I"
  236. },
  237. {
  238. re: /[\xEC-\xEF]/g,
  239. ch: "i"
  240. },
  241. {
  242. re: /[\xD2-\xD6]/g,
  243. ch: "O"
  244. },
  245. {
  246. re: /[\xF2-\xF6]/g,
  247. ch: "o"
  248. },
  249. {
  250. re: /[\xD9-\xDC]/g,
  251. ch: "U"
  252. },
  253. {
  254. re: /[\xF9-\xFC]/g,
  255. ch: "u"
  256. },
  257. {
  258. re: /[\xC7-\xE7]/g,
  259. ch: "c"
  260. },
  261. {
  262. re: /[\xD1]/g,
  263. ch: "N"
  264. },
  265. {
  266. re: /[\xF1]/g,
  267. ch: "n"
  268. }
  269. ];
  270. $.each(rExps, function() {
  271. text = text ? text.replace(this.re, this.ch) : '';
  272. });
  273. return text;
  274. }
  275. // List of HTML entities for escaping.
  276. var escapeMap = {
  277. '&': '&amp;',
  278. '<': '&lt;',
  279. '>': '&gt;',
  280. '"': '&quot;',
  281. "'": '&#x27;',
  282. '`': '&#x60;'
  283. };
  284. var unescapeMap = {
  285. '&amp;': '&',
  286. '&lt;': '<',
  287. '&gt;': '>',
  288. '&quot;': '"',
  289. '&#x27;': "'",
  290. '&#x60;': '`'
  291. };
  292. // Functions for escaping and unescaping strings to/from HTML interpolation.
  293. var createEscaper = function(map) {
  294. var escaper = function(match) {
  295. return map[match];
  296. };
  297. // Regexes for identifying a key that needs to be escaped.
  298. var source = '(?:' + Object.keys(map).join('|') + ')';
  299. var testRegexp = RegExp(source);
  300. var replaceRegexp = RegExp(source, 'g');
  301. return function(string) {
  302. string = string == null ? '' : '' + string;
  303. return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
  304. };
  305. };
  306. var htmlEscape = createEscaper(escapeMap);
  307. var htmlUnescape = createEscaper(unescapeMap);
  308. var Selectpicker = function(element, options) {
  309. // bootstrap-select has been initialized - revert valHooks.select.set back to its original function
  310. if (!valHooks.useDefault) {
  311. $.valHooks.select.set = valHooks._set;
  312. valHooks.useDefault = true;
  313. }
  314. this.$element = $(element);
  315. this.$newElement = null;
  316. this.$button = null;
  317. this.$menu = null;
  318. this.$lis = null;
  319. this.options = options;
  320. // 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
  321. // data-attribute)
  322. if (this.options.title === null) {
  323. this.options.title = this.$element.attr('title');
  324. }
  325. // Format window padding
  326. var winPad = this.options.windowPadding;
  327. if (typeof winPad === 'number') {
  328. this.options.windowPadding = [winPad, winPad, winPad, winPad];
  329. }
  330. //Expose public methods
  331. this.val = Selectpicker.prototype.val;
  332. this.render = Selectpicker.prototype.render;
  333. this.refresh = Selectpicker.prototype.refresh;
  334. this.setStyle = Selectpicker.prototype.setStyle;
  335. this.selectAll = Selectpicker.prototype.selectAll;
  336. this.deselectAll = Selectpicker.prototype.deselectAll;
  337. this.destroy = Selectpicker.prototype.destroy;
  338. this.remove = Selectpicker.prototype.remove;
  339. this.show = Selectpicker.prototype.show;
  340. this.hide = Selectpicker.prototype.hide;
  341. this.init();
  342. };
  343. Selectpicker.VERSION = '1.12.2';
  344. // part of this is duplicated in i18n/defaults-en_US.js. Make sure to update both.
  345. Selectpicker.DEFAULTS = {
  346. noneSelectedText: 'Nothing selected',
  347. noneResultsText: 'No results matched {0}',
  348. countSelectedText: function(numSelected, numTotal) {
  349. return (numSelected == 1) ? "{0} item selected" : "{0} items selected";
  350. },
  351. maxOptionsText: function(numAll, numGroup) {
  352. return [
  353. (numAll == 1) ? 'Limit reached ({n} item max)' : 'Limit reached ({n} items max)',
  354. (numGroup == 1) ? 'Group limit reached ({n} item max)' : 'Group limit reached ({n} items max)'
  355. ];
  356. },
  357. selectAllText: 'Select All',
  358. deselectAllText: 'Deselect All',
  359. doneButton: false,
  360. doneButtonText: 'Close',
  361. multipleSeparator: ', ',
  362. styleBase: 'btn',
  363. style: 'btn-default',
  364. size: 'auto',
  365. title: null,
  366. selectedTextFormat: 'values',
  367. width: false,
  368. container: false,
  369. hideDisabled: false,
  370. showSubtext: false,
  371. showIcon: true,
  372. showContent: true,
  373. dropupAuto: true,
  374. header: false,
  375. liveSearch: false,
  376. liveSearchPlaceholder: null,
  377. liveSearchNormalize: false,
  378. liveSearchStyle: 'contains',
  379. actionsBox: false,
  380. iconBase: 'material-icons',
  381. tickIcon: 'done',
  382. showTick: false,
  383. template: {
  384. caret: '<span class="caret"></span>'
  385. },
  386. maxOptions: false,
  387. mobile: false,
  388. selectOnTab: false,
  389. dropdownAlignRight: false,
  390. windowPadding: 0
  391. };
  392. Selectpicker.prototype = {
  393. constructor: Selectpicker,
  394. init: function() {
  395. var that = this,
  396. id = this.$element.attr('id');
  397. this.$element.addClass('bs-select-hidden');
  398. // store originalIndex (key) and newIndex (value) in this.liObj for fast accessibility
  399. // allows us to do this.$lis.eq(that.liObj[index]) instead of this.$lis.filter('[data-original-index="' + index + '"]')
  400. this.liObj = {};
  401. this.multiple = this.$element.prop('multiple');
  402. this.autofocus = this.$element.prop('autofocus');
  403. this.$newElement = this.createView();
  404. this.$element
  405. .after(this.$newElement)
  406. .appendTo(this.$newElement);
  407. this.$button = this.$newElement.children('button');
  408. this.$menu = this.$newElement.children('.dropdown-menu');
  409. this.$menuInner = this.$menu.children('.inner');
  410. this.$searchbox = this.$menu.find('input');
  411. this.$element.removeClass('bs-select-hidden');
  412. if (this.options.dropdownAlignRight === true) this.$menu.addClass('dropdown-menu-right');
  413. if (typeof id !== 'undefined') {
  414. this.$button.attr('data-id', id);
  415. $('label[for="' + id + '"]').click(function(e) {
  416. e.preventDefault();
  417. that.$button.focus();
  418. });
  419. }
  420. this.checkDisabled();
  421. this.clickListener();
  422. if (this.options.liveSearch) this.liveSearchListener();
  423. this.render();
  424. this.setStyle();
  425. this.setWidth();
  426. if (this.options.container) this.selectPosition();
  427. this.$menu.data('this', this);
  428. this.$newElement.data('this', this);
  429. if (this.options.mobile) this.mobile();
  430. this.$newElement.on({
  431. 'hide.bs.dropdown': function(e) {
  432. that.$menuInner.attr('aria-expanded', false);
  433. that.$element.trigger('hide.bs.select', e);
  434. },
  435. 'hidden.bs.dropdown': function(e) {
  436. that.$element.trigger('hidden.bs.select', e);
  437. },
  438. 'show.bs.dropdown': function(e) {
  439. that.$menuInner.attr('aria-expanded', true);
  440. that.$element.trigger('show.bs.select', e);
  441. },
  442. 'shown.bs.dropdown': function(e) {
  443. that.$element.trigger('shown.bs.select', e);
  444. }
  445. });
  446. if (that.$element[0].hasAttribute('required')) {
  447. this.$element.on('invalid', function() {
  448. that.$button
  449. .addClass('bs-invalid')
  450. .focus();
  451. that.$element.on({
  452. 'focus.bs.select': function() {
  453. that.$button.focus();
  454. that.$element.off('focus.bs.select');
  455. },
  456. 'shown.bs.select': function() {
  457. that.$element
  458. .val(that.$element.val()) // set the value to hide the validation message in Chrome when menu is opened
  459. .off('shown.bs.select');
  460. },
  461. 'rendered.bs.select': function() {
  462. // if select is no longer invalid, remove the bs-invalid class
  463. if (this.validity.valid) that.$button.removeClass('bs-invalid');
  464. that.$element.off('rendered.bs.select');
  465. }
  466. });
  467. });
  468. }
  469. setTimeout(function() {
  470. that.$element.trigger('loaded.bs.select');
  471. });
  472. },
  473. createDropdown: function() {
  474. // Options
  475. // If we are multiple or showTick option is set, then add the show-tick class
  476. var showTick = (this.multiple || this.options.showTick) ? ' show-tick' : '',
  477. inputGroup = this.$element.parent().hasClass('input-group') ? ' input-group-btn' : '',
  478. autofocus = this.autofocus ? ' autofocus' : '';
  479. // Elements
  480. var header = this.options.header ? '<div class="popover-title"><button type="button" class="close" aria-hidden="true">&times;</button>' + this.options.header + '</div>' : '';
  481. var searchbox = this.options.liveSearch ?
  482. '<div class="bs-searchbox">' +
  483. '<input type="text" class="form-control" autocomplete="off"' +
  484. (null === this.options.liveSearchPlaceholder ? '' : ' placeholder="' + htmlEscape(this.options.liveSearchPlaceholder) + '"') + ' role="textbox" aria-label="Search">' +
  485. '</div>' :
  486. '';
  487. var actionsbox = this.multiple && this.options.actionsBox ?
  488. '<div class="bs-actionsbox">' +
  489. '<div class="btn-group btn-group-sm btn-block">' +
  490. '<button type="button" class="actions-btn bs-select-all btn btn-default">' +
  491. this.options.selectAllText +
  492. '</button>' +
  493. '<button type="button" class="actions-btn bs-deselect-all btn btn-default">' +
  494. this.options.deselectAllText +
  495. '</button>' +
  496. '</div>' +
  497. '</div>' :
  498. '';
  499. var donebutton = this.multiple && this.options.doneButton ?
  500. '<div class="bs-donebutton">' +
  501. '<div class="btn-group btn-block">' +
  502. '<button type="button" class="btn btn-sm btn-default">' +
  503. this.options.doneButtonText +
  504. '</button>' +
  505. '</div>' +
  506. '</div>' :
  507. '';
  508. var drop =
  509. '<div class="btn-group bootstrap-select' + showTick + inputGroup + '">' +
  510. '<button type="button" class="' + this.options.styleBase + ' dropdown-toggle" data-toggle="dropdown"' + autofocus + ' role="button">' +
  511. '<span class="filter-option pull-left"></span>&nbsp;' +
  512. '<span class="bs-caret">' +
  513. this.options.template.caret +
  514. '</span>' +
  515. '</button>' +
  516. '<div class="dropdown-menu open" role="combobox">' +
  517. header +
  518. searchbox +
  519. actionsbox +
  520. '<ul class="dropdown-menu inner" role="listbox" aria-expanded="false">' +
  521. '</ul>' +
  522. donebutton +
  523. '</div>' +
  524. '</div>';
  525. return $(drop);
  526. },
  527. createView: function() {
  528. var $drop = this.createDropdown(),
  529. li = this.createLi();
  530. $drop.find('ul')[0].innerHTML = li;
  531. return $drop;
  532. },
  533. reloadLi: function() {
  534. // rebuild
  535. var li = this.createLi();
  536. this.$menuInner[0].innerHTML = li;
  537. },
  538. createLi: function() {
  539. var that = this,
  540. _li = [],
  541. optID = 0,
  542. titleOption = document.createElement('option'),
  543. liIndex = -1; // increment liIndex whenever a new <li> element is created to ensure liObj is correct
  544. // Helper functions
  545. /**
  546. * @param content
  547. * @param [index]
  548. * @param [classes]
  549. * @param [optgroup]
  550. * @returns {string}
  551. */
  552. var generateLI = function(content, index, classes, optgroup) {
  553. return '<li' +
  554. ((typeof classes !== 'undefined' & '' !== classes) ? ' class="' + classes + '"' : '') +
  555. ((typeof index !== 'undefined' & null !== index) ? ' data-original-index="' + index + '"' : '') +
  556. ((typeof optgroup !== 'undefined' & null !== optgroup) ? 'data-optgroup="' + optgroup + '"' : '') +
  557. '>' + content + '</li>';
  558. };
  559. /**
  560. * @param text
  561. * @param [classes]
  562. * @param [inline]
  563. * @param [tokens]
  564. * @returns {string}
  565. */
  566. var generateA = function(text, classes, inline, tokens) {
  567. return '<a tabindex="0"' +
  568. (typeof classes !== 'undefined' ? ' class="' + classes + '"' : '') +
  569. (inline ? ' style="' + inline + '"' : '') +
  570. (that.options.liveSearchNormalize ? ' data-normalized-text="' + normalizeToBase(htmlEscape($(text).html())) + '"' : '') +
  571. (typeof tokens !== 'undefined' || tokens !== null ? ' data-tokens="' + tokens + '"' : '') +
  572. ' role="option">' + text +
  573. '<span class="' + that.options.iconBase + ' check-mark"> ' + that.options.tickIcon + ' </span>' +
  574. '</a>';
  575. };
  576. if (this.options.title && !this.multiple) {
  577. // this option doesn't create a new <li> element, but does add a new option, so liIndex is decreased
  578. // since liObj is recalculated on every refresh, liIndex needs to be decreased even if the titleOption is already appended
  579. liIndex--;
  580. if (!this.$element.find('.bs-title-option').length) {
  581. // Use native JS to prepend option (faster)
  582. var element = this.$element[0];
  583. titleOption.className = 'bs-title-option';
  584. titleOption.innerHTML = this.options.title;
  585. titleOption.value = '';
  586. element.insertBefore(titleOption, element.firstChild);
  587. // Check if selected or data-selected attribute is already set on an option. If not, select the titleOption option.
  588. // the selected item may have been changed by user or programmatically before the bootstrap select plugin runs,
  589. // if so, the select will have the data-selected attribute
  590. var $opt = $(element.options[element.selectedIndex]);
  591. if ($opt.attr('selected') === undefined && this.$element.data('selected') === undefined) {
  592. titleOption.selected = true;
  593. }
  594. }
  595. }
  596. this.$element.find('option').each(function(index) {
  597. var $this = $(this);
  598. liIndex++;
  599. if ($this.hasClass('bs-title-option')) return;
  600. // Get the class and text for the option
  601. var optionClass = this.className || '',
  602. inline = this.style.cssText,
  603. text = $this.data('content') ? $this.data('content') : $this.html(),
  604. tokens = $this.data('tokens') ? $this.data('tokens') : null,
  605. subtext = typeof $this.data('subtext') !== 'undefined' ? '<small class="text-muted">' + $this.data('subtext') + '</small>' : '',
  606. icon = typeof $this.data('icon') !== 'undefined' ? '<span class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></span> ' : '',
  607. $parent = $this.parent(),
  608. isOptgroup = $parent[0].tagName === 'OPTGROUP',
  609. isOptgroupDisabled = isOptgroup && $parent[0].disabled,
  610. isDisabled = this.disabled || isOptgroupDisabled;
  611. if (icon !== '' && isDisabled) {
  612. icon = '<span>' + icon + '</span>';
  613. }
  614. if (that.options.hideDisabled && (isDisabled && !isOptgroup || isOptgroupDisabled)) {
  615. liIndex--;
  616. return;
  617. }
  618. if (!$this.data('content')) {
  619. // Prepend any icon and append any subtext to the main text.
  620. text = icon + '<span class="text">' + text + subtext + '</span>';
  621. }
  622. if (isOptgroup && $this.data('divider') !== true) {
  623. if (that.options.hideDisabled && isDisabled) {
  624. if ($parent.data('allOptionsDisabled') === undefined) {
  625. var $options = $parent.children();
  626. $parent.data('allOptionsDisabled', $options.filter(':disabled').length === $options.length);
  627. }
  628. if ($parent.data('allOptionsDisabled')) {
  629. liIndex--;
  630. return;
  631. }
  632. }
  633. var optGroupClass = ' ' + $parent[0].className || '';
  634. if ($this.index() === 0) { // Is it the first option of the optgroup?
  635. optID += 1;
  636. // Get the opt group label
  637. var label = $parent[0].label,
  638. labelSubtext = typeof $parent.data('subtext') !== 'undefined' ? '<small class="text-muted">' + $parent.data('subtext') + '</small>' : '',
  639. labelIcon = $parent.data('icon') ? '<span class="' + that.options.iconBase + ' ' + $parent.data('icon') + '"></span> ' : '';
  640. label = labelIcon + '<span class="text">' + htmlEscape(label) + labelSubtext + '</span>';
  641. if (index !== 0 && _li.length > 0) { // Is it NOT the first option of the select && are there elements in the dropdown?
  642. liIndex++;
  643. _li.push(generateLI('', null, 'divider', optID + 'div'));
  644. }
  645. liIndex++;
  646. _li.push(generateLI(label, null, 'dropdown-header' + optGroupClass, optID));
  647. }
  648. if (that.options.hideDisabled && isDisabled) {
  649. liIndex--;
  650. return;
  651. }
  652. _li.push(generateLI(generateA(text, 'opt ' + optionClass + optGroupClass, inline, tokens), index, '', optID));
  653. } else if ($this.data('divider') === true) {
  654. _li.push(generateLI('', index, 'divider'));
  655. } else if ($this.data('hidden') === true) {
  656. _li.push(generateLI(generateA(text, optionClass, inline, tokens), index, 'hidden is-hidden'));
  657. } else {
  658. var showDivider = this.previousElementSibling && this.previousElementSibling.tagName === 'OPTGROUP';
  659. // if previous element is not an optgroup and hideDisabled is true
  660. if (!showDivider && that.options.hideDisabled) {
  661. // get previous elements
  662. var $prev = $(this).prevAll();
  663. for (var i = 0; i < $prev.length; i++) {
  664. // find the first element in the previous elements that is an optgroup
  665. if ($prev[i].tagName === 'OPTGROUP') {
  666. var optGroupDistance = 0;
  667. // loop through the options in between the current option and the optgroup
  668. // and check if they are hidden or disabled
  669. for (var d = 0; d < i; d++) {
  670. var prevOption = $prev[d];
  671. if (prevOption.disabled || $(prevOption).data('hidden') === true) optGroupDistance++;
  672. }
  673. // if all of the options between the current option and the optgroup are hidden or disabled, show the divider
  674. if (optGroupDistance === i) showDivider = true;
  675. break;
  676. }
  677. }
  678. }
  679. if (showDivider) {
  680. liIndex++;
  681. _li.push(generateLI('', null, 'divider', optID + 'div'));
  682. }
  683. _li.push(generateLI(generateA(text, optionClass, inline, tokens), index));
  684. }
  685. that.liObj[index] = liIndex;
  686. });
  687. //If we are not multiple, we don't have a selected item, and we don't have a title, select the first element so something is set in the button
  688. if (!this.multiple && this.$element.find('option:selected').length === 0 && !this.options.title) {
  689. this.$element.find('option').eq(0).prop('selected', true).attr('selected', 'selected');
  690. }
  691. return _li.join('');
  692. },
  693. findLis: function() {
  694. if (this.$lis == null) this.$lis = this.$menu.find('li');
  695. return this.$lis;
  696. },
  697. /**
  698. * @param [updateLi] defaults to true
  699. */
  700. render: function(updateLi) {
  701. var that = this,
  702. notDisabled;
  703. //Update the LI to match the SELECT
  704. if (updateLi !== false) {
  705. this.$element.find('option').each(function(index) {
  706. var $lis = that.findLis().eq(that.liObj[index]);
  707. that.setDisabled(index, this.disabled || this.parentNode.tagName === 'OPTGROUP' && this.parentNode.disabled, $lis);
  708. that.setSelected(index, this.selected, $lis);
  709. });
  710. }
  711. this.togglePlaceholder();
  712. this.tabIndex();
  713. var selectedItems = this.$element.find('option').map(function() {
  714. if (this.selected) {
  715. if (that.options.hideDisabled && (this.disabled || this.parentNode.tagName === 'OPTGROUP' && this.parentNode.disabled)) return;
  716. var $this = $(this),
  717. icon = $this.data('icon') && that.options.showIcon ? '<i class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></i> ' : '',
  718. subtext;
  719. if (that.options.showSubtext && $this.data('subtext') && !that.multiple) {
  720. subtext = ' <small class="text-muted">' + $this.data('subtext') + '</small>';
  721. } else {
  722. subtext = '';
  723. }
  724. if (typeof $this.attr('title') !== 'undefined') {
  725. return $this.attr('title');
  726. } else if ($this.data('content') && that.options.showContent) {
  727. return $this.data('content').toString();
  728. } else {
  729. return icon + $this.html() + subtext;
  730. }
  731. }
  732. }).toArray();
  733. //Fixes issue in IE10 occurring when no default option is selected and at least one option is disabled
  734. //Convert all the values into a comma delimited string
  735. var title = !this.multiple ? selectedItems[0] : selectedItems.join(this.options.multipleSeparator);
  736. //If this is multi select, and the selectText type is count, the show 1 of 2 selected etc..
  737. if (this.multiple && this.options.selectedTextFormat.indexOf('count') > -1) {
  738. var max = this.options.selectedTextFormat.split('>');
  739. if ((max.length > 1 && selectedItems.length > max[1]) || (max.length == 1 && selectedItems.length >= 2)) {
  740. notDisabled = this.options.hideDisabled ? ', [disabled]' : '';
  741. var totalCount = this.$element.find('option').not('[data-divider="true"], [data-hidden="true"]' + notDisabled).length,
  742. tr8nText = (typeof this.options.countSelectedText === 'function') ? this.options.countSelectedText(selectedItems.length, totalCount) : this.options.countSelectedText;
  743. title = tr8nText.replace('{0}', selectedItems.length.toString()).replace('{1}', totalCount.toString());
  744. }
  745. }
  746. if (this.options.title == undefined) {
  747. this.options.title = this.$element.attr('title');
  748. }
  749. if (this.options.selectedTextFormat == 'static') {
  750. title = this.options.title;
  751. }
  752. //If we dont have a title, then use the default, or if nothing is set at all, use the not selected text
  753. if (!title) {
  754. title = typeof this.options.title !== 'undefined' ? this.options.title : this.options.noneSelectedText;
  755. }
  756. //strip all HTML tags and trim the result, then unescape any escaped tags
  757. this.$button.attr('title', htmlUnescape($.trim(title.replace(/<[^>]*>?/g, ''))));
  758. this.$button.children('.filter-option').html(title);
  759. this.$element.trigger('rendered.bs.select');
  760. },
  761. /**
  762. * @param [style]
  763. * @param [status]
  764. */
  765. setStyle: function(style, status) {
  766. if (this.$element.attr('class')) {
  767. this.$newElement.addClass(this.$element.attr('class').replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi, ''));
  768. }
  769. var buttonClass = style ? style : this.options.style;
  770. if (status == 'add') {
  771. this.$button.addClass(buttonClass);
  772. } else if (status == 'remove') {
  773. this.$button.removeClass(buttonClass);
  774. } else {
  775. this.$button.removeClass(this.options.style);
  776. this.$button.addClass(buttonClass);
  777. }
  778. },
  779. liHeight: function(refresh) {
  780. if (!refresh && (this.options.size === false || this.sizeInfo)) return;
  781. var newElement = document.createElement('div'),
  782. menu = document.createElement('div'),
  783. menuInner = document.createElement('ul'),
  784. divider = document.createElement('li'),
  785. li = document.createElement('li'),
  786. a = document.createElement('a'),
  787. text = document.createElement('span'),
  788. header = this.options.header && this.$menu.find('.popover-title').length > 0 ? this.$menu.find('.popover-title')[0].cloneNode(true) : null,
  789. search = this.options.liveSearch ? document.createElement('div') : null,
  790. actions = this.options.actionsBox && this.multiple && this.$menu.find('.bs-actionsbox').length > 0 ? this.$menu.find('.bs-actionsbox')[0].cloneNode(true) : null,
  791. doneButton = this.options.doneButton && this.multiple && this.$menu.find('.bs-donebutton').length > 0 ? this.$menu.find('.bs-donebutton')[0].cloneNode(true) : null;
  792. text.className = 'text';
  793. newElement.className = this.$menu[0].parentNode.className + ' open';
  794. menu.className = 'dropdown-menu open';
  795. menuInner.className = 'dropdown-menu inner';
  796. divider.className = 'divider';
  797. text.appendChild(document.createTextNode('Inner text'));
  798. a.appendChild(text);
  799. li.appendChild(a);
  800. menuInner.appendChild(li);
  801. menuInner.appendChild(divider);
  802. if (header) menu.appendChild(header);
  803. if (search) {
  804. var input = document.createElement('input');
  805. search.className = 'bs-searchbox';
  806. input.className = 'form-control';
  807. search.appendChild(input);
  808. menu.appendChild(search);
  809. }
  810. if (actions) menu.appendChild(actions);
  811. menu.appendChild(menuInner);
  812. if (doneButton) menu.appendChild(doneButton);
  813. newElement.appendChild(menu);
  814. document.body.appendChild(newElement);
  815. var liHeight = a.offsetHeight,
  816. headerHeight = header ? header.offsetHeight : 0,
  817. searchHeight = search ? search.offsetHeight : 0,
  818. actionsHeight = actions ? actions.offsetHeight : 0,
  819. doneButtonHeight = doneButton ? doneButton.offsetHeight : 0,
  820. dividerHeight = $(divider).outerHeight(true),
  821. // fall back to jQuery if getComputedStyle is not supported
  822. menuStyle = typeof getComputedStyle === 'function' ? getComputedStyle(menu) : false,
  823. $menu = menuStyle ? null : $(menu),
  824. menuPadding = {
  825. vert: parseInt(menuStyle ? menuStyle.paddingTop : $menu.css('paddingTop')) +
  826. parseInt(menuStyle ? menuStyle.paddingBottom : $menu.css('paddingBottom')) +
  827. parseInt(menuStyle ? menuStyle.borderTopWidth : $menu.css('borderTopWidth')) +
  828. parseInt(menuStyle ? menuStyle.borderBottomWidth : $menu.css('borderBottomWidth')),
  829. horiz: parseInt(menuStyle ? menuStyle.paddingLeft : $menu.css('paddingLeft')) +
  830. parseInt(menuStyle ? menuStyle.paddingRight : $menu.css('paddingRight')) +
  831. parseInt(menuStyle ? menuStyle.borderLeftWidth : $menu.css('borderLeftWidth')) +
  832. parseInt(menuStyle ? menuStyle.borderRightWidth : $menu.css('borderRightWidth'))
  833. },
  834. menuExtras = {
  835. vert: menuPadding.vert +
  836. parseInt(menuStyle ? menuStyle.marginTop : $menu.css('marginTop')) +
  837. parseInt(menuStyle ? menuStyle.marginBottom : $menu.css('marginBottom')) + 2,
  838. horiz: menuPadding.horiz +
  839. parseInt(menuStyle ? menuStyle.marginLeft : $menu.css('marginLeft')) +
  840. parseInt(menuStyle ? menuStyle.marginRight : $menu.css('marginRight')) + 2
  841. }
  842. document.body.removeChild(newElement);
  843. this.sizeInfo = {
  844. liHeight: liHeight,
  845. headerHeight: headerHeight,
  846. searchHeight: searchHeight,
  847. actionsHeight: actionsHeight,
  848. doneButtonHeight: doneButtonHeight,
  849. dividerHeight: dividerHeight,
  850. menuPadding: menuPadding,
  851. menuExtras: menuExtras
  852. };
  853. },
  854. setSize: function() {
  855. this.findLis();
  856. this.liHeight();
  857. if (this.options.header) this.$menu.css('padding-top', 0);
  858. if (this.options.size === false) return;
  859. var that = this,
  860. $menu = this.$menu,
  861. $menuInner = this.$menuInner,
  862. $window = $(window),
  863. selectHeight = this.$newElement[0].offsetHeight,
  864. selectWidth = this.$newElement[0].offsetWidth,
  865. liHeight = this.sizeInfo['liHeight'],
  866. headerHeight = this.sizeInfo['headerHeight'],
  867. searchHeight = this.sizeInfo['searchHeight'],
  868. actionsHeight = this.sizeInfo['actionsHeight'],
  869. doneButtonHeight = this.sizeInfo['doneButtonHeight'],
  870. divHeight = this.sizeInfo['dividerHeight'],
  871. menuPadding = this.sizeInfo['menuPadding'],
  872. menuExtras = this.sizeInfo['menuExtras'],
  873. notDisabled = this.options.hideDisabled ? '.disabled' : '',
  874. menuHeight,
  875. menuWidth,
  876. getHeight,
  877. getWidth,
  878. selectOffsetTop,
  879. selectOffsetBot,
  880. selectOffsetLeft,
  881. selectOffsetRight,
  882. getPos = function() {
  883. var pos = that.$newElement.offset(),
  884. $container = $(that.options.container),
  885. containerPos;
  886. if (that.options.container && !$container.is('body')) {
  887. containerPos = $container.offset();
  888. containerPos.top += parseInt($container.css('borderTopWidth'));
  889. containerPos.left += parseInt($container.css('borderLeftWidth'));
  890. } else {
  891. containerPos = {
  892. top: 0,
  893. left: 0
  894. };
  895. }
  896. var winPad = that.options.windowPadding;
  897. selectOffsetTop = pos.top - containerPos.top - $window.scrollTop();
  898. selectOffsetBot = $window.height() - selectOffsetTop - selectHeight - containerPos.top - winPad[2];
  899. selectOffsetLeft = pos.left - containerPos.left - $window.scrollLeft();
  900. selectOffsetRight = $window.width() - selectOffsetLeft - selectWidth - containerPos.left - winPad[1];
  901. selectOffsetTop -= winPad[0];
  902. selectOffsetLeft -= winPad[3];
  903. };
  904. getPos();
  905. if (this.options.size === 'auto') {
  906. var getSize = function() {
  907. var minHeight,
  908. hasClass = function(className, include) {
  909. return function(element) {
  910. if (include) {
  911. return (element.classList ? element.classList.contains(className) : $(element).hasClass(className));
  912. } else {
  913. return !(element.classList ? element.classList.contains(className) : $(element).hasClass(className));
  914. }
  915. };
  916. },
  917. lis = that.$menuInner[0].getElementsByTagName('li'),
  918. lisVisible = Array.prototype.filter ? Array.prototype.filter.call(lis, hasClass('hidden', false)) : that.$lis.not('.hidden'),
  919. optGroup = Array.prototype.filter ? Array.prototype.filter.call(lisVisible, hasClass('dropdown-header', true)) : lisVisible.filter('.dropdown-header');
  920. getPos();
  921. menuHeight = selectOffsetBot - menuExtras.vert;
  922. menuWidth = selectOffsetRight - menuExtras.horiz;
  923. if (that.options.container) {
  924. if (!$menu.data('height')) $menu.data('height', $menu.height());
  925. getHeight = $menu.data('height');
  926. if (!$menu.data('width')) $menu.data('width', $menu.width());
  927. getWidth = $menu.data('width');
  928. } else {
  929. getHeight = $menu.height();
  930. getWidth = $menu.width();
  931. }
  932. if (that.options.dropupAuto) {
  933. that.$newElement.toggleClass('dropup', selectOffsetTop > selectOffsetBot && (menuHeight - menuExtras.vert) < getHeight);
  934. }
  935. if (that.$newElement.hasClass('dropup')) {
  936. menuHeight = selectOffsetTop - menuExtras.vert;
  937. }
  938. if (that.options.dropdownAlignRight === 'auto') {
  939. $menu.toggleClass('dropdown-menu-right', selectOffsetLeft > selectOffsetRight && (menuWidth - menuExtras.horiz) < (getWidth - selectWidth));
  940. }
  941. if ((lisVisible.length + optGroup.length) > 3) {
  942. minHeight = liHeight * 3 + menuExtras.vert - 2;
  943. } else {
  944. minHeight = 0;
  945. }
  946. $menu.css({
  947. 'max-height': menuHeight + 'px',
  948. 'overflow': 'hidden',
  949. 'min-height': minHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight + 'px'
  950. });
  951. $menuInner.css({
  952. 'max-height': menuHeight - headerHeight - searchHeight - actionsHeight - doneButtonHeight - menuPadding.vert + 'px',
  953. 'overflow-y': 'auto',
  954. 'min-height': Math.max(minHeight - menuPadding.vert, 0) + 'px'
  955. });
  956. };
  957. getSize();
  958. this.$searchbox.off('input.getSize propertychange.getSize').on('input.getSize propertychange.getSize', getSize);
  959. $window.off('resize.getSize scroll.getSize').on('resize.getSize scroll.getSize', getSize);
  960. } else if (this.options.size && this.options.size != 'auto' && this.$lis.not(notDisabled).length > this.options.size) {
  961. var optIndex = this.$lis.not('.divider').not(notDisabled).children().slice(0, this.options.size).last().parent().index(),
  962. divLength = this.$lis.slice(0, optIndex + 1).filter('.divider').length;
  963. menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding.vert;
  964. if (that.options.container) {
  965. if (!$menu.data('height')) $menu.data('height', $menu.height());
  966. getHeight = $menu.data('height');
  967. } else {
  968. getHeight = $menu.height();
  969. }
  970. if (that.options.dropupAuto) {
  971. //noinspection JSUnusedAssignment
  972. this.$newElement.toggleClass('dropup', selectOffsetTop > selectOffsetBot && (menuHeight - menuExtras.vert) < getHeight);
  973. }
  974. $menu.css({
  975. 'max-height': menuHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight + 'px',
  976. 'overflow': 'hidden',
  977. 'min-height': ''
  978. });
  979. $menuInner.css({
  980. 'max-height': menuHeight - menuPadding.vert + 'px',
  981. 'overflow-y': 'auto',
  982. 'min-height': ''
  983. });
  984. }
  985. },
  986. setWidth: function() {
  987. if (this.options.width === 'auto') {
  988. this.$menu.css('min-width', '0');
  989. // Get correct width if element is hidden
  990. var $selectClone = this.$menu.parent().clone().appendTo('body'),
  991. $selectClone2 = this.options.container ? this.$newElement.clone().appendTo('body') : $selectClone,
  992. ulWidth = $selectClone.children('.dropdown-menu').outerWidth(),
  993. btnWidth = $selectClone2.css('width', 'auto').children('button').outerWidth();
  994. $selectClone.remove();
  995. $selectClone2.remove();
  996. // Set width to whatever's larger, button title or longest option
  997. this.$newElement.css('width', Math.max(ulWidth, btnWidth) + 'px');
  998. } else if (this.options.width === 'fit') {
  999. // Remove inline min-width so width can be changed from 'auto'
  1000. this.$menu.css('min-width', '');
  1001. this.$newElement.css('width', '').addClass('fit-width');
  1002. } else if (this.options.width) {
  1003. // Remove inline min-width so width can be changed from 'auto'
  1004. this.$menu.css('min-width', '');
  1005. this.$newElement.css('width', this.options.width);
  1006. } else {
  1007. // Remove inline min-width/width so width can be changed
  1008. this.$menu.css('min-width', '');
  1009. this.$newElement.css('width', '');
  1010. }
  1011. // Remove fit-width class if width is changed programmatically
  1012. if (this.$newElement.hasClass('fit-width') && this.options.width !== 'fit') {
  1013. this.$newElement.removeClass('fit-width');
  1014. }
  1015. },
  1016. selectPosition: function() {
  1017. this.$bsContainer = $('<div class="bs-container" />');
  1018. var that = this,
  1019. $container = $(this.options.container),
  1020. pos,
  1021. containerPos,
  1022. actualHeight,
  1023. getPlacement = function($element) {
  1024. that.$bsContainer.addClass($element.attr('class').replace(/form-control|fit-width/gi, '')).toggleClass('dropup', $element.hasClass('dropup'));
  1025. pos = $element.offset();
  1026. if (!$container.is('body')) {
  1027. containerPos = $container.offset();
  1028. containerPos.top += parseInt($container.css('borderTopWidth')) - $container.scrollTop();
  1029. containerPos.left += parseInt($container.css('borderLeftWidth')) - $container.scrollLeft();
  1030. } else {
  1031. containerPos = {
  1032. top: 0,
  1033. left: 0
  1034. };
  1035. }
  1036. actualHeight = $element.hasClass('dropup') ? 0 : $element[0].offsetHeight;
  1037. that.$bsContainer.css({
  1038. 'top': pos.top - containerPos.top + actualHeight,
  1039. 'left': pos.left - containerPos.left,
  1040. 'width': $element[0].offsetWidth
  1041. });
  1042. };
  1043. this.$button.on('click', function() {
  1044. var $this = $(this);
  1045. if (that.isDisabled()) {
  1046. return;
  1047. }
  1048. getPlacement(that.$newElement);
  1049. that.$bsContainer
  1050. .appendTo(that.options.container)
  1051. .toggleClass('open', !$this.hasClass('open'))
  1052. .append(that.$menu);
  1053. });
  1054. $(window).on('resize scroll', function() {
  1055. getPlacement(that.$newElement);
  1056. });
  1057. this.$element.on('hide.bs.select', function() {
  1058. that.$menu.data('height', that.$menu.height());
  1059. that.$bsContainer.detach();
  1060. });
  1061. },
  1062. /**
  1063. * @param {number} index - the index of the option that is being changed
  1064. * @param {boolean} selected - true if the option is being selected, false if being deselected
  1065. * @param {JQuery} $lis - the 'li' element that is being modified
  1066. */
  1067. setSelected: function(index, selected, $lis) {
  1068. if (!$lis) {
  1069. this.togglePlaceholder(); // check if setSelected is being called by changing the value of the select
  1070. $lis = this.findLis().eq(this.liObj[index]);
  1071. }
  1072. $lis.toggleClass('selected', selected).find('a').attr('aria-selected', selected);
  1073. },
  1074. /**
  1075. * @param {number} index - the index of the option that is being disabled
  1076. * @param {boolean} disabled - true if the option is being disabled, false if being enabled
  1077. * @param {JQuery} $lis - the 'li' element that is being modified
  1078. */
  1079. setDisabled: function(index, disabled, $lis) {
  1080. if (!$lis) {
  1081. $lis = this.findLis().eq(this.liObj[index]);
  1082. }
  1083. if (disabled) {
  1084. $lis.addClass('disabled').children('a').attr('href', '#').attr('tabindex', -1).attr('aria-disabled', true);
  1085. } else {
  1086. $lis.removeClass('disabled').children('a').removeAttr('href').attr('tabindex', 0).attr('aria-disabled', false);
  1087. }
  1088. },
  1089. isDisabled: function() {
  1090. return this.$element[0].disabled;
  1091. },
  1092. checkDisabled: function() {
  1093. var that = this;
  1094. if (this.isDisabled()) {
  1095. this.$newElement.addClass('disabled');
  1096. this.$button.addClass('disabled').attr('tabindex', -1).attr('aria-disabled', true);
  1097. } else {
  1098. if (this.$button.hasClass('disabled')) {
  1099. this.$newElement.removeClass('disabled');
  1100. this.$button.removeClass('disabled').attr('aria-disabled', false);
  1101. }
  1102. if (this.$button.attr('tabindex') == -1 && !this.$element.data('tabindex')) {
  1103. this.$button.removeAttr('tabindex');
  1104. }
  1105. }
  1106. this.$button.click(function() {
  1107. return !that.isDisabled();
  1108. });
  1109. },
  1110. togglePlaceholder: function() {
  1111. var value = this.$element.val();
  1112. this.$button.toggleClass('bs-placeholder', value === null || value === '' || (value.constructor === Array && value.length === 0));
  1113. },
  1114. tabIndex: function() {
  1115. if (this.$element.data('tabindex') !== this.$element.attr('tabindex') &&
  1116. (this.$element.attr('tabindex') !== -98 && this.$element.attr('tabindex') !== '-98')) {
  1117. this.$element.data('tabindex', this.$element.attr('tabindex'));
  1118. this.$button.attr('tabindex', this.$element.data('tabindex'));
  1119. }
  1120. this.$element.attr('tabindex', -98);
  1121. },
  1122. clickListener: function() {
  1123. var that = this,
  1124. $document = $(document);
  1125. $document.data('spaceSelect', false);
  1126. this.$button.on('keyup', function(e) {
  1127. if (/(32)/.test(e.keyCode.toString(10)) && $document.data('spaceSelect')) {
  1128. e.preventDefault();
  1129. $document.data('spaceSelect', false);
  1130. }
  1131. });
  1132. this.$button.on('click', function() {
  1133. that.setSize();
  1134. });
  1135. this.$element.on('shown.bs.select', function() {
  1136. if (!that.options.liveSearch && !that.multiple) {
  1137. that.$menuInner.find('.selected a').focus();
  1138. } else if (!that.multiple) {
  1139. var selectedIndex = that.liObj[that.$element[0].selectedIndex];
  1140. if (typeof selectedIndex !== 'number' || that.options.size === false) return;
  1141. // scroll to selected option
  1142. var offset = that.$lis.eq(selectedIndex)[0].offsetTop - that.$menuInner[0].offsetTop;
  1143. offset = offset - that.$menuInner[0].offsetHeight / 2 + that.sizeInfo.liHeight / 2;
  1144. that.$menuInner[0].scrollTop = offset;
  1145. }
  1146. });
  1147. this.$menuInner.on('click', 'li a', function(e) {
  1148. var $this = $(this),
  1149. clickedIndex = $this.parent().data('originalIndex'),
  1150. prevValue = that.$element.val(),
  1151. prevIndex = that.$element.prop('selectedIndex'),
  1152. triggerChange = true;
  1153. // Don't close on multi choice menu
  1154. if (that.multiple && that.options.maxOptions !== 1) {
  1155. e.stopPropagation();
  1156. }
  1157. e.preventDefault();
  1158. //Don't run if we have been disabled
  1159. if (!that.isDisabled() && !$this.parent().hasClass('disabled')) {
  1160. var $options = that.$element.find('option'),
  1161. $option = $options.eq(clickedIndex),
  1162. state = $option.prop('selected'),
  1163. $optgroup = $option.parent('optgroup'),
  1164. maxOptions = that.options.maxOptions,
  1165. maxOptionsGrp = $optgroup.data('maxOptions') || false;
  1166. if (!that.multiple) { // Deselect all others if not multi select box
  1167. $options.prop('selected', false);
  1168. $option.prop('selected', true);
  1169. that.$menuInner.find('.selected').removeClass('selected').find('a').attr('aria-selected', false);
  1170. that.setSelected(clickedIndex, true);
  1171. } else { // Toggle the one we have chosen if we are multi select.
  1172. $option.prop('selected', !state);
  1173. that.setSelected(clickedIndex, !state);
  1174. $this.blur();
  1175. if (maxOptions !== false || maxOptionsGrp !== false) {
  1176. var maxReached = maxOptions < $options.filter(':selected').length,
  1177. maxReachedGrp = maxOptionsGrp < $optgroup.find('option:selected').length;
  1178. if ((maxOptions && maxReached) || (maxOptionsGrp && maxReachedGrp)) {
  1179. if (maxOptions && maxOptions == 1) {
  1180. $options.prop('selected', false);
  1181. $option.prop('selected', true);
  1182. that.$menuInner.find('.selected').removeClass('selected');
  1183. that.setSelected(clickedIndex, true);
  1184. } else if (maxOptionsGrp && maxOptionsGrp == 1) {
  1185. $optgroup.find('option:selected').prop('selected', false);
  1186. $option.prop('selected', true);
  1187. var optgroupID = $this.parent().data('optgroup');
  1188. that.$menuInner.find('[data-optgroup="' + optgroupID + '"]').removeClass('selected');
  1189. that.setSelected(clickedIndex, true);
  1190. } else {
  1191. var maxOptionsText = typeof that.options.maxOptionsText === 'string' ? [that.options.maxOptionsText, that.options.maxOptionsText] : that.options.maxOptionsText,
  1192. maxOptionsArr = typeof maxOptionsText === 'function' ? maxOptionsText(maxOptions, maxOptionsGrp) : maxOptionsText,
  1193. maxTxt = maxOptionsArr[0].replace('{n}', maxOptions),
  1194. maxTxtGrp = maxOptionsArr[1].replace('{n}', maxOptionsGrp),
  1195. $notify = $('<div class="notify"></div>');
  1196. // If {var} is set in array, replace it
  1197. /** @deprecated */
  1198. if (maxOptionsArr[2]) {
  1199. maxTxt = maxTxt.replace('{var}', maxOptionsArr[2][maxOptions > 1 ? 0 : 1]);
  1200. maxTxtGrp = maxTxtGrp.replace('{var}', maxOptionsArr[2][maxOptionsGrp > 1 ? 0 : 1]);
  1201. }
  1202. $option.prop('selected', false);
  1203. that.$menu.append($notify);
  1204. if (maxOptions && maxReached) {
  1205. $notify.append($('<div>' + maxTxt + '</div>'));
  1206. triggerChange = false;
  1207. that.$element.trigger('maxReached.bs.select');
  1208. }
  1209. if (maxOptionsGrp && maxReachedGrp) {
  1210. $notify.append($('<div>' + maxTxtGrp + '</div>'));
  1211. triggerChange = false;
  1212. that.$element.trigger('maxReachedGrp.bs.select');
  1213. }
  1214. setTimeout(function() {
  1215. that.setSelected(clickedIndex, false);
  1216. }, 10);
  1217. $notify.delay(750).fadeOut(300, function() {
  1218. $(this).remove();
  1219. });
  1220. }
  1221. }
  1222. }
  1223. }
  1224. if (!that.multiple || (that.multiple && that.options.maxOptions === 1)) {
  1225. that.$button.focus();
  1226. } else if (that.options.liveSearch) {
  1227. that.$searchbox.focus();
  1228. }
  1229. // Trigger select 'change'
  1230. if (triggerChange) {
  1231. if ((prevValue != that.$element.val() && that.multiple) || (prevIndex != that.$element.prop('selectedIndex') && !that.multiple)) {
  1232. // $option.prop('selected') is current option state (selected/unselected). state is previous option state.
  1233. changed_arguments = [clickedIndex, $option.prop('selected'), state];
  1234. that.$element
  1235. .triggerNative('change');
  1236. }
  1237. }
  1238. }
  1239. });
  1240. this.$menu.on('click', 'li.disabled a, .popover-title, .popover-title :not(.close)', function(e) {
  1241. if (e.currentTarget == this) {
  1242. e.preventDefault();
  1243. e.stopPropagation();
  1244. if (that.options.liveSearch && !$(e.target).hasClass('close')) {
  1245. that.$searchbox.focus();
  1246. } else {
  1247. that.$button.focus();
  1248. }
  1249. }
  1250. });
  1251. this.$menuInner.on('click', '.divider, .dropdown-header', function(e) {
  1252. e.preventDefault();
  1253. e.stopPropagation();
  1254. if (that.options.liveSearch) {
  1255. that.$searchbox.focus();
  1256. } else {
  1257. that.$button.focus();
  1258. }
  1259. });
  1260. this.$menu.on('click', '.popover-title .close', function() {
  1261. that.$button.click();
  1262. });
  1263. this.$searchbox.on('click', function(e) {
  1264. e.stopPropagation();
  1265. });
  1266. this.$menu.on('click', '.actions-btn', function(e) {
  1267. if (that.options.liveSearch) {
  1268. that.$searchbox.focus();
  1269. } else {
  1270. that.$button.focus();
  1271. }
  1272. e.preventDefault();
  1273. e.stopPropagation();
  1274. if ($(this).hasClass('bs-select-all')) {
  1275. that.selectAll();
  1276. } else {
  1277. that.deselectAll();
  1278. }
  1279. });
  1280. this.$element.change(function() {
  1281. that.render(false);
  1282. that.$element.trigger('changed.bs.select', changed_arguments);
  1283. changed_arguments = null;
  1284. });
  1285. },
  1286. liveSearchListener: function() {
  1287. var that = this,
  1288. $no_results = $('<li class="no-results"></li>');
  1289. this.$button.on('click.dropdown.data-api', function() {
  1290. that.$menuInner.find('.active').removeClass('active');
  1291. if (!!that.$searchbox.val()) {
  1292. that.$searchbox.val('');
  1293. that.$lis.not('.is-hidden').removeClass('hidden');
  1294. if (!!$no_results.parent().length) $no_results.remove();
  1295. }
  1296. if (!that.multiple) that.$menuInner.find('.selected').addClass('active');
  1297. setTimeout(function() {
  1298. that.$searchbox.focus();
  1299. }, 10);
  1300. });
  1301. this.$searchbox.on('click.dropdown.data-api focus.dropdown.data-api touchend.dropdown.data-api', function(e) {
  1302. e.stopPropagation();
  1303. });
  1304. this.$searchbox.on('input propertychange', function() {
  1305. that.$lis.not('.is-hidden').removeClass('hidden');
  1306. that.$lis.filter('.active').removeClass('active');
  1307. $no_results.remove();
  1308. if (that.$searchbox.val()) {
  1309. var $searchBase = that.$lis.not('.is-hidden, .divider, .dropdown-header'),
  1310. $hideItems;
  1311. if (that.options.liveSearchNormalize) {
  1312. $hideItems = $searchBase.find('a').not(':a' + that._searchStyle() + '("' + normalizeToBase(that.$searchbox.val()) + '")');
  1313. } else {
  1314. $hideItems = $searchBase.find('a').not(':' + that._searchStyle() + '("' + that.$searchbox.val() + '")');
  1315. }
  1316. if ($hideItems.length === $searchBase.length) {
  1317. $no_results.html(that.options.noneResultsText.replace('{0}', '"' + htmlEscape(that.$searchbox.val()) + '"'));
  1318. that.$menuInner.append($no_results);
  1319. that.$lis.addClass('hidden');
  1320. } else {
  1321. $hideItems.parent().addClass('hidden');
  1322. var $lisVisible = that.$lis.not('.hidden'),
  1323. $foundDiv;
  1324. // hide divider if first or last visible, or if followed by another divider
  1325. $lisVisible.each(function(index) {
  1326. var $this = $(this);
  1327. if ($this.hasClass('divider')) {
  1328. if ($foundDiv === undefined) {
  1329. $this.addClass('hidden');
  1330. } else {
  1331. if ($foundDiv) $foundDiv.addClass('hidden');
  1332. $foundDiv = $this;
  1333. }
  1334. } else if ($this.hasClass('dropdown-header') && $lisVisible.eq(index + 1).data('optgroup') !== $this.data('optgroup')) {
  1335. $this.addClass('hidden');
  1336. } else {
  1337. $foundDiv = null;
  1338. }
  1339. });
  1340. if ($foundDiv) $foundDiv.addClass('hidden');
  1341. $searchBase.not('.hidden').first().addClass('active');
  1342. }
  1343. }
  1344. });
  1345. },
  1346. _searchStyle: function() {
  1347. var styles = {
  1348. begins: 'ibegins',
  1349. startsWith: 'ibegins'
  1350. };
  1351. return styles[this.options.liveSearchStyle] || 'icontains';
  1352. },
  1353. val: function(value) {
  1354. if (typeof value !== 'undefined') {
  1355. this.$element.val(value);
  1356. this.render();
  1357. return this.$element;
  1358. } else {
  1359. return this.$element.val();
  1360. }
  1361. },
  1362. changeAll: function(status) {
  1363. if (!this.multiple) return;
  1364. if (typeof status === 'undefined') status = true;
  1365. this.findLis();
  1366. var $options = this.$element.find('option'),
  1367. $lisVisible = this.$lis.not('.divider, .dropdown-header, .disabled, .hidden'),
  1368. lisVisLen = $lisVisible.length,
  1369. selectedOptions = [];
  1370. if (status) {
  1371. if ($lisVisible.filter('.selected').length === $lisVisible.length) return;
  1372. } else {
  1373. if ($lisVisible.filter('.selected').length === 0) return;
  1374. }
  1375. $lisVisible.toggleClass('selected', status);
  1376. for (var i = 0; i < lisVisLen; i++) {
  1377. var origIndex = $lisVisible[i].getAttribute('data-original-index');
  1378. selectedOptions[selectedOptions.length] = $options.eq(origIndex)[0];
  1379. }
  1380. $(selectedOptions).prop('selected', status);
  1381. this.render(false);
  1382. this.togglePlaceholder();
  1383. this.$element
  1384. .triggerNative('change');
  1385. },
  1386. selectAll: function() {
  1387. return this.changeAll(true);
  1388. },
  1389. deselectAll: function() {
  1390. return this.changeAll(false);
  1391. },
  1392. toggle: function(e) {
  1393. e = e || window.event;
  1394. if (e) e.stopPropagation();
  1395. this.$button.trigger('click');
  1396. },
  1397. keydown: function(e) {
  1398. var $this = $(this),
  1399. $parent = $this.is('input') ? $this.parent().parent() : $this.parent(),
  1400. $items,
  1401. that = $parent.data('this'),
  1402. index,
  1403. next,
  1404. first,
  1405. last,
  1406. prev,
  1407. nextPrev,
  1408. prevIndex,
  1409. isActive,
  1410. selector = ':not(.disabled, .hidden, .dropdown-header, .divider)',
  1411. keyCodeMap = {
  1412. 32: ' ',
  1413. 48: '0',
  1414. 49: '1',
  1415. 50: '2',
  1416. 51: '3',
  1417. 52: '4',
  1418. 53: '5',
  1419. 54: '6',
  1420. 55: '7',
  1421. 56: '8',
  1422. 57: '9',
  1423. 59: ';',
  1424. 65: 'a',
  1425. 66: 'b',
  1426. 67: 'c',
  1427. 68: 'd',
  1428. 69: 'e',
  1429. 70: 'f',
  1430. 71: 'g',
  1431. 72: 'h',
  1432. 73: 'i',
  1433. 74: 'j',
  1434. 75: 'k',
  1435. 76: 'l',
  1436. 77: 'm',
  1437. 78: 'n',
  1438. 79: 'o',
  1439. 80: 'p',
  1440. 81: 'q',
  1441. 82: 'r',
  1442. 83: 's',
  1443. 84: 't',
  1444. 85: 'u',
  1445. 86: 'v',
  1446. 87: 'w',
  1447. 88: 'x',
  1448. 89: 'y',
  1449. 90: 'z',
  1450. 96: '0',
  1451. 97: '1',
  1452. 98: '2',
  1453. 99: '3',
  1454. 100: '4',
  1455. 101: '5',
  1456. 102: '6',
  1457. 103: '7',
  1458. 104: '8',
  1459. 105: '9'
  1460. };
  1461. if (that.options.liveSearch) $parent = $this.parent().parent();
  1462. if (that.options.container) $parent = that.$menu;
  1463. $items = $('[role="listbox"] li', $parent);
  1464. isActive = that.$newElement.hasClass('open');
  1465. if (!isActive && (e.keyCode >= 48 && e.keyCode <= 57 || e.keyCode >= 96 && e.keyCode <= 105 || e.keyCode >= 65 && e.keyCode <= 90)) {
  1466. if (!that.options.container) {
  1467. that.setSize();
  1468. that.$menu.parent().addClass('open');
  1469. isActive = true;
  1470. } else {
  1471. that.$button.trigger('click');
  1472. }
  1473. that.$searchbox.focus();
  1474. return;
  1475. }
  1476. if (that.options.liveSearch) {
  1477. if (/(^9$|27)/.test(e.keyCode.toString(10)) && isActive) {
  1478. e.preventDefault();
  1479. e.stopPropagation();
  1480. that.$menuInner.click();
  1481. that.$button.focus();
  1482. }
  1483. // $items contains li elements when liveSearch is enabled
  1484. $items = $('[role="listbox"] li' + selector, $parent);
  1485. if (!$this.val() && !/(38|40)/.test(e.keyCode.toString(10))) {
  1486. if ($items.filter('.active').length === 0) {
  1487. $items = that.$menuInner.find('li');
  1488. if (that.options.liveSearchNormalize) {
  1489. $items = $items.filter(':a' + that._searchStyle() + '(' + normalizeToBase(keyCodeMap[e.keyCode]) + ')');
  1490. } else {
  1491. $items = $items.filter(':' + that._searchStyle() + '(' + keyCodeMap[e.keyCode] + ')');
  1492. }
  1493. }
  1494. }
  1495. }
  1496. if (!$items.length) return;
  1497. if (/(38|40)/.test(e.keyCode.toString(10))) {
  1498. index = $items.index($items.find('a').filter(':focus').parent());
  1499. first = $items.filter(selector).first().index();
  1500. last = $items.filter(selector).last().index();
  1501. next = $items.eq(index).nextAll(selector).eq(0).index();
  1502. prev = $items.eq(index).prevAll(selector).eq(0).index();
  1503. nextPrev = $items.eq(next).prevAll(selector).eq(0).index();
  1504. if (that.options.liveSearch) {
  1505. $items.each(function(i) {
  1506. if (!$(this).hasClass('disabled')) {
  1507. $(this).data('index', i);
  1508. }
  1509. });
  1510. index = $items.index($items.filter('.active'));
  1511. first = $items.first().data('index');
  1512. last = $items.last().data('index');
  1513. next = $items.eq(index).nextAll().eq(0).data('index');
  1514. prev = $items.eq(index).prevAll().eq(0).data('index');
  1515. nextPrev = $items.eq(next).prevAll().eq(0).data('index');
  1516. }
  1517. prevIndex = $this.data('prevIndex');
  1518. if (e.keyCode == 38) {
  1519. if (that.options.liveSearch) index--;
  1520. if (index != nextPrev && index > prev) index = prev;
  1521. if (index < first) index = first;
  1522. if (index == prevIndex) index = last;
  1523. } else if (e.keyCode == 40) {
  1524. if (that.options.liveSearch) index++;
  1525. if (index == -1) index = 0;
  1526. if (index != nextPrev && index < next) index = next;
  1527. if (index > last) index = last;
  1528. if (index == prevIndex) index = first;
  1529. }
  1530. $this.data('prevIndex', index);
  1531. if (!that.options.liveSearch) {
  1532. $items.eq(index).children('a').focus();
  1533. } else {
  1534. e.preventDefault();
  1535. if (!$this.hasClass('dropdown-toggle')) {
  1536. $items.removeClass('active').eq(index).addClass('active').children('a').focus();
  1537. $this.focus();
  1538. }
  1539. }
  1540. } else if (!$this.is('input')) {
  1541. var keyIndex = [],
  1542. count,
  1543. prevKey;
  1544. $items.each(function() {
  1545. if (!$(this).hasClass('disabled')) {
  1546. if ($.trim($(this).children('a').text().toLowerCase()).substring(0, 1) == keyCodeMap[e.keyCode]) {
  1547. keyIndex.push($(this).index());
  1548. }
  1549. }
  1550. });
  1551. count = $(document).data('keycount');
  1552. count++;
  1553. $(document).data('keycount', count);
  1554. prevKey = $.trim($(':focus').text().toLowerCase()).substring(0, 1);
  1555. if (prevKey != keyCodeMap[e.keyCode]) {
  1556. count = 1;
  1557. $(document).data('keycount', count);
  1558. } else if (count >= keyIndex.length) {
  1559. $(document).data('keycount', 0);
  1560. if (count > keyIndex.length) count = 1;
  1561. }
  1562. $items.eq(keyIndex[count - 1]).children('a').focus();
  1563. }
  1564. // Select focused option if "Enter", "Spacebar" or "Tab" (when selectOnTab is true) are pressed inside the menu.
  1565. if ((/(13|32)/.test(e.keyCode.toString(10)) || (/(^9$)/.test(e.keyCode.toString(10)) && that.options.selectOnTab)) && isActive) {
  1566. if (!/(32)/.test(e.keyCode.toString(10))) e.preventDefault();
  1567. if (!that.options.liveSearch) {
  1568. var elem = $(':focus');
  1569. elem.click();
  1570. // Bring back focus for multiselects
  1571. elem.focus();
  1572. // Prevent screen from scrolling if the user hit the spacebar
  1573. e.preventDefault();
  1574. // Fixes spacebar selection of dropdown items in FF & IE
  1575. $(document).data('spaceSelect', true);
  1576. } else if (!/(32)/.test(e.keyCode.toString(10))) {
  1577. that.$menuInner.find('.active a').click();
  1578. $this.focus();
  1579. }
  1580. $(document).data('keycount', 0);
  1581. }
  1582. if ((/(^9$|27)/.test(e.keyCode.toString(10)) && isActive && (that.multiple || that.options.liveSearch)) || (/(27)/.test(e.keyCode.toString(10)) && !isActive)) {
  1583. that.$menu.parent().removeClass('open');
  1584. if (that.options.container) that.$newElement.removeClass('open');
  1585. that.$button.focus();
  1586. }
  1587. },
  1588. mobile: function() {
  1589. this.$element.addClass('mobile-device');
  1590. },
  1591. refresh: function() {
  1592. this.$lis = null;
  1593. this.liObj = {};
  1594. this.reloadLi();
  1595. this.render();
  1596. this.checkDisabled();
  1597. this.liHeight(true);
  1598. this.setStyle();
  1599. this.setWidth();
  1600. if (this.$lis) this.$searchbox.trigger('propertychange');
  1601. this.$element.trigger('refreshed.bs.select');
  1602. },
  1603. hide: function() {
  1604. this.$newElement.hide();
  1605. },
  1606. show: function() {
  1607. this.$newElement.show();
  1608. },
  1609. remove: function() {
  1610. this.$newElement.remove();
  1611. this.$element.remove();
  1612. },
  1613. destroy: function() {
  1614. this.$newElement.before(this.$element).remove();
  1615. if (this.$bsContainer) {
  1616. this.$bsContainer.remove();
  1617. } else {
  1618. this.$menu.remove();
  1619. }
  1620. this.$element
  1621. .off('.bs.select')
  1622. .removeData('selectpicker')
  1623. .removeClass('bs-select-hidden selectpicker');
  1624. }
  1625. };
  1626. // SELECTPICKER PLUGIN DEFINITION
  1627. // ==============================
  1628. function Plugin(option) {
  1629. // get the args of the outer function..
  1630. var args = arguments;
  1631. // The arguments of the function are explicitly re-defined from the argument list, because the shift causes them
  1632. // to get lost/corrupted in android 2.3 and IE9 #715 #775
  1633. var _option = option;
  1634. [].shift.apply(args);
  1635. var value;
  1636. var chain = this.each(function() {
  1637. var $this = $(this);
  1638. if ($this.is('select')) {
  1639. var data = $this.data('selectpicker'),
  1640. options = typeof _option == 'object' && _option;
  1641. if (!data) {
  1642. var config = $.extend({}, Selectpicker.DEFAULTS, $.fn.selectpicker.defaults || {}, $this.data(), options);
  1643. config.template = $.extend({}, Selectpicker.DEFAULTS.template, ($.fn.selectpicker.defaults ? $.fn.selectpicker.defaults.template : {}), $this.data().template, options.template);
  1644. $this.data('selectpicker', (data = new Selectpicker(this, config)));
  1645. } else if (options) {
  1646. for (var i in options) {
  1647. if (options.hasOwnProperty(i)) {
  1648. data.options[i] = options[i];
  1649. }
  1650. }
  1651. }
  1652. if (typeof _option == 'string') {
  1653. if (data[_option] instanceof Function) {
  1654. value = data[_option].apply(data, args);
  1655. } else {
  1656. value = data.options[_option];
  1657. }
  1658. }
  1659. }
  1660. });
  1661. if (typeof value !== 'undefined') {
  1662. //noinspection JSUnusedAssignment
  1663. return value;
  1664. } else {
  1665. return chain;
  1666. }
  1667. }
  1668. var old = $.fn.selectpicker;
  1669. $.fn.selectpicker = Plugin;
  1670. $.fn.selectpicker.Constructor = Selectpicker;
  1671. // SELECTPICKER NO CONFLICT
  1672. // ========================
  1673. $.fn.selectpicker.noConflict = function() {
  1674. $.fn.selectpicker = old;
  1675. return this;
  1676. };
  1677. $(document)
  1678. .data('keycount', 0)
  1679. .on('keydown.bs.select', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role="listbox"], .bs-searchbox input', Selectpicker.prototype.keydown)
  1680. .on('focusin.modal', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role="listbox"], .bs-searchbox input', function(e) {
  1681. e.stopPropagation();
  1682. });
  1683. // SELECTPICKER DATA-API
  1684. // =====================
  1685. $(window).on('load.bs.select.data-api', function() {
  1686. $('.selectpicker').each(function() {
  1687. var $selectpicker = $(this);
  1688. Plugin.call($selectpicker, $selectpicker.data());
  1689. })
  1690. });
  1691. })(jQuery);
  1692. }));