bootstrap-select.js 68 KB

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