bootstrap-select.js 68 KB

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