1
0

bootstrap-select.js 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896
  1. /*!
  2. * Bootstrap-select v1.12.1 (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 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.1';
  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. // create a span instead of input as creating an input element is slower
  764. var input = document.createElement('span');
  765. search.className = 'bs-searchbox';
  766. input.className = 'form-control';
  767. search.appendChild(input);
  768. menu.appendChild(search);
  769. }
  770. if (actions) menu.appendChild(actions);
  771. menu.appendChild(menuInner);
  772. if (doneButton) menu.appendChild(doneButton);
  773. newElement.appendChild(menu);
  774. document.body.appendChild(newElement);
  775. var liHeight = a.offsetHeight,
  776. headerHeight = header ? header.offsetHeight : 0,
  777. searchHeight = search ? search.offsetHeight : 0,
  778. actionsHeight = actions ? actions.offsetHeight : 0,
  779. doneButtonHeight = doneButton ? doneButton.offsetHeight : 0,
  780. dividerHeight = $(divider).outerHeight(true),
  781. // fall back to jQuery if getComputedStyle is not supported
  782. menuStyle = typeof getComputedStyle === 'function' ? getComputedStyle(menu) : false,
  783. $menu = menuStyle ? null : $(menu),
  784. menuPadding = {
  785. vert: parseInt(menuStyle ? menuStyle.paddingTop : $menu.css('paddingTop')) +
  786. parseInt(menuStyle ? menuStyle.paddingBottom : $menu.css('paddingBottom')) +
  787. parseInt(menuStyle ? menuStyle.borderTopWidth : $menu.css('borderTopWidth')) +
  788. parseInt(menuStyle ? menuStyle.borderBottomWidth : $menu.css('borderBottomWidth')),
  789. horiz: parseInt(menuStyle ? menuStyle.paddingLeft : $menu.css('paddingLeft')) +
  790. parseInt(menuStyle ? menuStyle.paddingRight : $menu.css('paddingRight')) +
  791. parseInt(menuStyle ? menuStyle.borderLeftWidth : $menu.css('borderLeftWidth')) +
  792. parseInt(menuStyle ? menuStyle.borderRightWidth : $menu.css('borderRightWidth'))
  793. },
  794. menuExtras = {
  795. vert: menuPadding.vert +
  796. parseInt(menuStyle ? menuStyle.marginTop : $menu.css('marginTop')) +
  797. parseInt(menuStyle ? menuStyle.marginBottom : $menu.css('marginBottom')) + 2,
  798. horiz: menuPadding.horiz +
  799. parseInt(menuStyle ? menuStyle.marginLeft : $menu.css('marginLeft')) +
  800. parseInt(menuStyle ? menuStyle.marginRight : $menu.css('marginRight')) + 2
  801. }
  802. document.body.removeChild(newElement);
  803. this.sizeInfo = {
  804. liHeight: liHeight,
  805. headerHeight: headerHeight,
  806. searchHeight: searchHeight,
  807. actionsHeight: actionsHeight,
  808. doneButtonHeight: doneButtonHeight,
  809. dividerHeight: dividerHeight,
  810. menuPadding: menuPadding,
  811. menuExtras: menuExtras
  812. };
  813. },
  814. setSize: function () {
  815. this.findLis();
  816. this.liHeight();
  817. if (this.options.header) this.$menu.css('padding-top', 0);
  818. if (this.options.size === false) return;
  819. var that = this,
  820. $menu = this.$menu,
  821. $menuInner = this.$menuInner,
  822. $window = $(window),
  823. selectHeight = this.$newElement[0].offsetHeight,
  824. selectWidth = this.$newElement[0].offsetWidth,
  825. liHeight = this.sizeInfo['liHeight'],
  826. headerHeight = this.sizeInfo['headerHeight'],
  827. searchHeight = this.sizeInfo['searchHeight'],
  828. actionsHeight = this.sizeInfo['actionsHeight'],
  829. doneButtonHeight = this.sizeInfo['doneButtonHeight'],
  830. divHeight = this.sizeInfo['dividerHeight'],
  831. menuPadding = this.sizeInfo['menuPadding'],
  832. menuExtras = this.sizeInfo['menuExtras'],
  833. notDisabled = this.options.hideDisabled ? '.disabled' : '',
  834. menuHeight,
  835. menuWidth,
  836. getHeight,
  837. getWidth,
  838. selectOffsetTop,
  839. selectOffsetBot,
  840. selectOffsetLeft,
  841. selectOffsetRight,
  842. getPos = function() {
  843. var pos = that.$newElement.offset(),
  844. $container = $(that.options.container),
  845. containerPos;
  846. if (that.options.container && !$container.is('body')) {
  847. containerPos = $container.offset();
  848. containerPos.top += parseInt($container.css('borderTopWidth'));
  849. containerPos.left += parseInt($container.css('borderLeftWidth'));
  850. } else {
  851. containerPos = { top: 0, left: 0 };
  852. }
  853. var winPad = that.options.windowPadding;
  854. selectOffsetTop = pos.top - containerPos.top - $window.scrollTop();
  855. selectOffsetBot = $window.height() - selectOffsetTop - selectHeight - containerPos.top - winPad[2];
  856. selectOffsetLeft = pos.left - containerPos.left - $window.scrollLeft();
  857. selectOffsetRight = $window.width() - selectOffsetLeft - selectWidth - containerPos.left - winPad[1];
  858. selectOffsetTop -= winPad[0];
  859. selectOffsetLeft -= winPad[3];
  860. };
  861. getPos();
  862. if (this.options.size === 'auto') {
  863. var getSize = function () {
  864. var minHeight,
  865. hasClass = function (className, include) {
  866. return function (element) {
  867. if (include) {
  868. return (element.classList ? element.classList.contains(className) : $(element).hasClass(className));
  869. } else {
  870. return !(element.classList ? element.classList.contains(className) : $(element).hasClass(className));
  871. }
  872. };
  873. },
  874. lis = that.$menuInner[0].getElementsByTagName('li'),
  875. lisVisible = Array.prototype.filter ? Array.prototype.filter.call(lis, hasClass('hidden', false)) : that.$lis.not('.hidden'),
  876. optGroup = Array.prototype.filter ? Array.prototype.filter.call(lisVisible, hasClass('dropdown-header', true)) : lisVisible.filter('.dropdown-header');
  877. getPos();
  878. menuHeight = selectOffsetBot - menuExtras.vert;
  879. menuWidth = selectOffsetRight - menuExtras.horiz;
  880. if (that.options.container) {
  881. if (!$menu.data('height')) $menu.data('height', $menu.height());
  882. getHeight = $menu.data('height');
  883. if (!$menu.data('width')) $menu.data('width', $menu.width());
  884. getWidth = $menu.data('width');
  885. } else {
  886. getHeight = $menu.height();
  887. getWidth = $menu.width();
  888. }
  889. if (that.options.dropupAuto) {
  890. that.$newElement.toggleClass('dropup', selectOffsetTop > selectOffsetBot && (menuHeight - menuExtras.vert) < getHeight);
  891. }
  892. if (that.$newElement.hasClass('dropup')) {
  893. menuHeight = selectOffsetTop - menuExtras.vert;
  894. }
  895. if (that.options.dropdownAlignRight === 'auto') {
  896. $menu.toggleClass('dropdown-menu-right', selectOffsetLeft > selectOffsetRight && (menuWidth - menuExtras.horiz) < (getWidth - selectWidth));
  897. }
  898. if ((lisVisible.length + optGroup.length) > 3) {
  899. minHeight = liHeight * 3 + menuExtras.vert - 2;
  900. } else {
  901. minHeight = 0;
  902. }
  903. $menu.css({
  904. 'max-height': menuHeight + 'px',
  905. 'overflow': 'hidden',
  906. 'min-height': minHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight + 'px'
  907. });
  908. $menuInner.css({
  909. 'max-height': menuHeight - headerHeight - searchHeight - actionsHeight - doneButtonHeight - menuPadding.vert + 'px',
  910. 'overflow-y': 'auto',
  911. 'min-height': Math.max(minHeight - menuPadding.vert, 0) + 'px'
  912. });
  913. };
  914. getSize();
  915. this.$searchbox.off('input.getSize propertychange.getSize').on('input.getSize propertychange.getSize', getSize);
  916. $window.off('resize.getSize scroll.getSize').on('resize.getSize scroll.getSize', getSize);
  917. } else if (this.options.size && this.options.size != 'auto' && this.$lis.not(notDisabled).length > this.options.size) {
  918. var optIndex = this.$lis.not('.divider').not(notDisabled).children().slice(0, this.options.size).last().parent().index(),
  919. divLength = this.$lis.slice(0, optIndex + 1).filter('.divider').length;
  920. menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding.vert;
  921. if (that.options.container) {
  922. if (!$menu.data('height')) $menu.data('height', $menu.height());
  923. getHeight = $menu.data('height');
  924. } else {
  925. getHeight = $menu.height();
  926. }
  927. if (that.options.dropupAuto) {
  928. //noinspection JSUnusedAssignment
  929. this.$newElement.toggleClass('dropup', selectOffsetTop > selectOffsetBot && (menuHeight - menuExtras.vert) < getHeight);
  930. }
  931. $menu.css({
  932. 'max-height': menuHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight + 'px',
  933. 'overflow': 'hidden',
  934. 'min-height': ''
  935. });
  936. $menuInner.css({
  937. 'max-height': menuHeight - menuPadding.vert + 'px',
  938. 'overflow-y': 'auto',
  939. 'min-height': ''
  940. });
  941. }
  942. },
  943. setWidth: function () {
  944. if (this.options.width === 'auto') {
  945. this.$menu.css('min-width', '0');
  946. // Get correct width if element is hidden
  947. var $selectClone = this.$menu.parent().clone().appendTo('body'),
  948. $selectClone2 = this.options.container ? this.$newElement.clone().appendTo('body') : $selectClone,
  949. ulWidth = $selectClone.children('.dropdown-menu').outerWidth(),
  950. btnWidth = $selectClone2.css('width', 'auto').children('button').outerWidth();
  951. $selectClone.remove();
  952. $selectClone2.remove();
  953. // Set width to whatever's larger, button title or longest option
  954. this.$newElement.css('width', Math.max(ulWidth, btnWidth) + 'px');
  955. } else if (this.options.width === 'fit') {
  956. // Remove inline min-width so width can be changed from 'auto'
  957. this.$menu.css('min-width', '');
  958. this.$newElement.css('width', '').addClass('fit-width');
  959. } else if (this.options.width) {
  960. // Remove inline min-width so width can be changed from 'auto'
  961. this.$menu.css('min-width', '');
  962. this.$newElement.css('width', this.options.width);
  963. } else {
  964. // Remove inline min-width/width so width can be changed
  965. this.$menu.css('min-width', '');
  966. this.$newElement.css('width', '');
  967. }
  968. // Remove fit-width class if width is changed programmatically
  969. if (this.$newElement.hasClass('fit-width') && this.options.width !== 'fit') {
  970. this.$newElement.removeClass('fit-width');
  971. }
  972. },
  973. selectPosition: function () {
  974. this.$bsContainer = $('<div class="bs-container" />');
  975. var that = this,
  976. $container = $(this.options.container),
  977. pos,
  978. containerPos,
  979. actualHeight,
  980. getPlacement = function ($element) {
  981. that.$bsContainer.addClass($element.attr('class').replace(/form-control|fit-width/gi, '')).toggleClass('dropup', $element.hasClass('dropup'));
  982. pos = $element.offset();
  983. if (!$container.is('body')) {
  984. containerPos = $container.offset();
  985. containerPos.top += parseInt($container.css('borderTopWidth')) - $container.scrollTop();
  986. containerPos.left += parseInt($container.css('borderLeftWidth')) - $container.scrollLeft();
  987. } else {
  988. containerPos = { top: 0, left: 0 };
  989. }
  990. actualHeight = $element.hasClass('dropup') ? 0 : $element[0].offsetHeight;
  991. that.$bsContainer.css({
  992. 'top': pos.top - containerPos.top + actualHeight,
  993. 'left': pos.left - containerPos.left,
  994. 'width': $element[0].offsetWidth
  995. });
  996. };
  997. this.$button.on('click', function () {
  998. var $this = $(this);
  999. if (that.isDisabled()) {
  1000. return;
  1001. }
  1002. getPlacement(that.$newElement);
  1003. that.$bsContainer
  1004. .appendTo(that.options.container)
  1005. .toggleClass('open', !$this.hasClass('open'))
  1006. .append(that.$menu);
  1007. });
  1008. $(window).on('resize scroll', function () {
  1009. getPlacement(that.$newElement);
  1010. });
  1011. this.$element.on('hide.bs.select', function () {
  1012. that.$menu.data('height', that.$menu.height());
  1013. that.$bsContainer.detach();
  1014. });
  1015. },
  1016. /**
  1017. * @param {number} index - the index of the option that is being changed
  1018. * @param {boolean} selected - true if the option is being selected, false if being deselected
  1019. * @param {JQuery} $lis - the 'li' element that is being modified
  1020. */
  1021. setSelected: function (index, selected, $lis) {
  1022. if (!$lis) {
  1023. this.togglePlaceholder(); // check if setSelected is being called by changing the value of the select
  1024. $lis = this.findLis().eq(this.liObj[index]);
  1025. }
  1026. $lis.toggleClass('selected', selected).find('a').attr('aria-selected', selected);
  1027. },
  1028. /**
  1029. * @param {number} index - the index of the option that is being disabled
  1030. * @param {boolean} disabled - true if the option is being disabled, false if being enabled
  1031. * @param {JQuery} $lis - the 'li' element that is being modified
  1032. */
  1033. setDisabled: function (index, disabled, $lis) {
  1034. if (!$lis) {
  1035. $lis = this.findLis().eq(this.liObj[index]);
  1036. }
  1037. if (disabled) {
  1038. $lis.addClass('disabled').children('a').attr('href', '#').attr('tabindex', -1).attr('aria-disabled', true);
  1039. } else {
  1040. $lis.removeClass('disabled').children('a').removeAttr('href').attr('tabindex', 0).attr('aria-disabled', false);
  1041. }
  1042. },
  1043. isDisabled: function () {
  1044. return this.$element[0].disabled;
  1045. },
  1046. checkDisabled: function () {
  1047. var that = this;
  1048. if (this.isDisabled()) {
  1049. this.$newElement.addClass('disabled');
  1050. this.$button.addClass('disabled').attr('tabindex', -1).attr('aria-disabled', true);
  1051. } else {
  1052. if (this.$button.hasClass('disabled')) {
  1053. this.$newElement.removeClass('disabled');
  1054. this.$button.removeClass('disabled').attr('aria-disabled', false);
  1055. }
  1056. if (this.$button.attr('tabindex') == -1 && !this.$element.data('tabindex')) {
  1057. this.$button.removeAttr('tabindex');
  1058. }
  1059. }
  1060. this.$button.click(function () {
  1061. return !that.isDisabled();
  1062. });
  1063. },
  1064. togglePlaceholder: function () {
  1065. var value = this.$element.val();
  1066. this.$button.toggleClass('bs-placeholder', value === null || value === '' || (value.constructor === Array && value.length === 0));
  1067. },
  1068. tabIndex: function () {
  1069. if (this.$element.data('tabindex') !== this.$element.attr('tabindex') &&
  1070. (this.$element.attr('tabindex') !== -98 && this.$element.attr('tabindex') !== '-98')) {
  1071. this.$element.data('tabindex', this.$element.attr('tabindex'));
  1072. this.$button.attr('tabindex', this.$element.data('tabindex'));
  1073. }
  1074. this.$element.attr('tabindex', -98);
  1075. },
  1076. clickListener: function () {
  1077. var that = this,
  1078. $document = $(document);
  1079. $document.data('spaceSelect', false);
  1080. this.$button.on('keyup', function (e) {
  1081. if (/(32)/.test(e.keyCode.toString(10)) && $document.data('spaceSelect')) {
  1082. e.preventDefault();
  1083. $document.data('spaceSelect', false);
  1084. }
  1085. });
  1086. this.$button.on('click', function () {
  1087. that.setSize();
  1088. });
  1089. this.$element.on('shown.bs.select', function () {
  1090. if (!that.options.liveSearch && !that.multiple) {
  1091. that.$menuInner.find('.selected a').focus();
  1092. } else if (!that.multiple) {
  1093. var selectedIndex = that.liObj[that.$element[0].selectedIndex];
  1094. if (typeof selectedIndex !== 'number' || that.options.size === false) return;
  1095. // scroll to selected option
  1096. var offset = that.$lis.eq(selectedIndex)[0].offsetTop - that.$menuInner[0].offsetTop;
  1097. offset = offset - that.$menuInner[0].offsetHeight/2 + that.sizeInfo.liHeight/2;
  1098. that.$menuInner[0].scrollTop = offset;
  1099. }
  1100. });
  1101. this.$menuInner.on('click', 'li a', function (e) {
  1102. var $this = $(this),
  1103. clickedIndex = $this.parent().data('originalIndex'),
  1104. prevValue = that.$element.val(),
  1105. prevIndex = that.$element.prop('selectedIndex'),
  1106. triggerChange = true;
  1107. // Don't close on multi choice menu
  1108. if (that.multiple && that.options.maxOptions !== 1) {
  1109. e.stopPropagation();
  1110. }
  1111. e.preventDefault();
  1112. //Don't run if we have been disabled
  1113. if (!that.isDisabled() && !$this.parent().hasClass('disabled')) {
  1114. var $options = that.$element.find('option'),
  1115. $option = $options.eq(clickedIndex),
  1116. state = $option.prop('selected'),
  1117. $optgroup = $option.parent('optgroup'),
  1118. maxOptions = that.options.maxOptions,
  1119. maxOptionsGrp = $optgroup.data('maxOptions') || false;
  1120. if (!that.multiple) { // Deselect all others if not multi select box
  1121. $options.prop('selected', false);
  1122. $option.prop('selected', true);
  1123. that.$menuInner.find('.selected').removeClass('selected').find('a').attr('aria-selected', false);
  1124. that.setSelected(clickedIndex, true);
  1125. } else { // Toggle the one we have chosen if we are multi select.
  1126. $option.prop('selected', !state);
  1127. that.setSelected(clickedIndex, !state);
  1128. $this.blur();
  1129. if (maxOptions !== false || maxOptionsGrp !== false) {
  1130. var maxReached = maxOptions < $options.filter(':selected').length,
  1131. maxReachedGrp = maxOptionsGrp < $optgroup.find('option:selected').length;
  1132. if ((maxOptions && maxReached) || (maxOptionsGrp && maxReachedGrp)) {
  1133. if (maxOptions && maxOptions == 1) {
  1134. $options.prop('selected', false);
  1135. $option.prop('selected', true);
  1136. that.$menuInner.find('.selected').removeClass('selected');
  1137. that.setSelected(clickedIndex, true);
  1138. } else if (maxOptionsGrp && maxOptionsGrp == 1) {
  1139. $optgroup.find('option:selected').prop('selected', false);
  1140. $option.prop('selected', true);
  1141. var optgroupID = $this.parent().data('optgroup');
  1142. that.$menuInner.find('[data-optgroup="' + optgroupID + '"]').removeClass('selected');
  1143. that.setSelected(clickedIndex, true);
  1144. } else {
  1145. var maxOptionsText = typeof that.options.maxOptionsText === 'string' ? [that.options.maxOptionsText, that.options.maxOptionsText] : that.options.maxOptionsText,
  1146. maxOptionsArr = typeof maxOptionsText === 'function' ? maxOptionsText(maxOptions, maxOptionsGrp) : maxOptionsText,
  1147. maxTxt = maxOptionsArr[0].replace('{n}', maxOptions),
  1148. maxTxtGrp = maxOptionsArr[1].replace('{n}', maxOptionsGrp),
  1149. $notify = $('<div class="notify"></div>');
  1150. // If {var} is set in array, replace it
  1151. /** @deprecated */
  1152. if (maxOptionsArr[2]) {
  1153. maxTxt = maxTxt.replace('{var}', maxOptionsArr[2][maxOptions > 1 ? 0 : 1]);
  1154. maxTxtGrp = maxTxtGrp.replace('{var}', maxOptionsArr[2][maxOptionsGrp > 1 ? 0 : 1]);
  1155. }
  1156. $option.prop('selected', false);
  1157. that.$menu.append($notify);
  1158. if (maxOptions && maxReached) {
  1159. $notify.append($('<div>' + maxTxt + '</div>'));
  1160. triggerChange = false;
  1161. that.$element.trigger('maxReached.bs.select');
  1162. }
  1163. if (maxOptionsGrp && maxReachedGrp) {
  1164. $notify.append($('<div>' + maxTxtGrp + '</div>'));
  1165. triggerChange = false;
  1166. that.$element.trigger('maxReachedGrp.bs.select');
  1167. }
  1168. setTimeout(function () {
  1169. that.setSelected(clickedIndex, false);
  1170. }, 10);
  1171. $notify.delay(750).fadeOut(300, function () {
  1172. $(this).remove();
  1173. });
  1174. }
  1175. }
  1176. }
  1177. }
  1178. if (!that.multiple || (that.multiple && that.options.maxOptions === 1)) {
  1179. that.$button.focus();
  1180. } else if (that.options.liveSearch) {
  1181. that.$searchbox.focus();
  1182. }
  1183. // Trigger select 'change'
  1184. if (triggerChange) {
  1185. if ((prevValue != that.$element.val() && that.multiple) || (prevIndex != that.$element.prop('selectedIndex') && !that.multiple)) {
  1186. // $option.prop('selected') is current option state (selected/unselected). state is previous option state.
  1187. changed_arguments = [clickedIndex, $option.prop('selected'), state];
  1188. that.$element
  1189. .triggerNative('change');
  1190. }
  1191. }
  1192. }
  1193. });
  1194. this.$menu.on('click', 'li.disabled a, .popover-title, .popover-title :not(.close)', function (e) {
  1195. if (e.currentTarget == this) {
  1196. e.preventDefault();
  1197. e.stopPropagation();
  1198. if (that.options.liveSearch && !$(e.target).hasClass('close')) {
  1199. that.$searchbox.focus();
  1200. } else {
  1201. that.$button.focus();
  1202. }
  1203. }
  1204. });
  1205. this.$menuInner.on('click', '.divider, .dropdown-header', function (e) {
  1206. e.preventDefault();
  1207. e.stopPropagation();
  1208. if (that.options.liveSearch) {
  1209. that.$searchbox.focus();
  1210. } else {
  1211. that.$button.focus();
  1212. }
  1213. });
  1214. this.$menu.on('click', '.popover-title .close', function () {
  1215. that.$button.click();
  1216. });
  1217. this.$searchbox.on('click', function (e) {
  1218. e.stopPropagation();
  1219. });
  1220. this.$menu.on('click', '.actions-btn', function (e) {
  1221. if (that.options.liveSearch) {
  1222. that.$searchbox.focus();
  1223. } else {
  1224. that.$button.focus();
  1225. }
  1226. e.preventDefault();
  1227. e.stopPropagation();
  1228. if ($(this).hasClass('bs-select-all')) {
  1229. that.selectAll();
  1230. } else {
  1231. that.deselectAll();
  1232. }
  1233. });
  1234. this.$element.change(function () {
  1235. that.render(false);
  1236. that.$element.trigger('changed.bs.select', changed_arguments);
  1237. changed_arguments = null;
  1238. });
  1239. },
  1240. liveSearchListener: function () {
  1241. var that = this,
  1242. $no_results = $('<li class="no-results"></li>');
  1243. this.$button.on('click.dropdown.data-api', function () {
  1244. that.$menuInner.find('.active').removeClass('active');
  1245. if (!!that.$searchbox.val()) {
  1246. that.$searchbox.val('');
  1247. that.$lis.not('.is-hidden').removeClass('hidden');
  1248. if (!!$no_results.parent().length) $no_results.remove();
  1249. }
  1250. if (!that.multiple) that.$menuInner.find('.selected').addClass('active');
  1251. setTimeout(function () {
  1252. that.$searchbox.focus();
  1253. }, 10);
  1254. });
  1255. this.$searchbox.on('click.dropdown.data-api focus.dropdown.data-api touchend.dropdown.data-api', function (e) {
  1256. e.stopPropagation();
  1257. });
  1258. this.$searchbox.on('input propertychange', function () {
  1259. that.$lis.not('.is-hidden').removeClass('hidden');
  1260. that.$lis.filter('.active').removeClass('active');
  1261. $no_results.remove();
  1262. if (that.$searchbox.val()) {
  1263. var $searchBase = that.$lis.not('.is-hidden, .divider, .dropdown-header'),
  1264. $hideItems;
  1265. if (that.options.liveSearchNormalize) {
  1266. $hideItems = $searchBase.not(':a' + that._searchStyle() + '("' + normalizeToBase(that.$searchbox.val()) + '")');
  1267. } else {
  1268. $hideItems = $searchBase.not(':' + that._searchStyle() + '("' + that.$searchbox.val() + '")');
  1269. }
  1270. if ($hideItems.length === $searchBase.length) {
  1271. $no_results.html(that.options.noneResultsText.replace('{0}', '"' + htmlEscape(that.$searchbox.val()) + '"'));
  1272. that.$menuInner.append($no_results);
  1273. that.$lis.addClass('hidden');
  1274. } else {
  1275. $hideItems.addClass('hidden');
  1276. var $lisVisible = that.$lis.not('.hidden'),
  1277. $foundDiv;
  1278. // hide divider if first or last visible, or if followed by another divider
  1279. $lisVisible.each(function (index) {
  1280. var $this = $(this);
  1281. if ($this.hasClass('divider')) {
  1282. if ($foundDiv === undefined) {
  1283. $this.addClass('hidden');
  1284. } else {
  1285. if ($foundDiv) $foundDiv.addClass('hidden');
  1286. $foundDiv = $this;
  1287. }
  1288. } else if ($this.hasClass('dropdown-header') && $lisVisible.eq(index + 1).data('optgroup') !== $this.data('optgroup')) {
  1289. $this.addClass('hidden');
  1290. } else {
  1291. $foundDiv = null;
  1292. }
  1293. });
  1294. if ($foundDiv) $foundDiv.addClass('hidden');
  1295. $searchBase.not('.hidden').first().addClass('active');
  1296. }
  1297. }
  1298. });
  1299. },
  1300. _searchStyle: function () {
  1301. var styles = {
  1302. begins: 'ibegins',
  1303. startsWith: 'ibegins'
  1304. };
  1305. return styles[this.options.liveSearchStyle] || 'icontains';
  1306. },
  1307. val: function (value) {
  1308. if (typeof value !== 'undefined') {
  1309. this.$element.val(value);
  1310. this.render();
  1311. return this.$element;
  1312. } else {
  1313. return this.$element.val();
  1314. }
  1315. },
  1316. changeAll: function (status) {
  1317. if (!this.multiple) return;
  1318. if (typeof status === 'undefined') status = true;
  1319. this.findLis();
  1320. var $options = this.$element.find('option'),
  1321. $lisVisible = this.$lis.not('.divider, .dropdown-header, .disabled, .hidden'),
  1322. lisVisLen = $lisVisible.length,
  1323. selectedOptions = [];
  1324. if (status) {
  1325. if ($lisVisible.filter('.selected').length === $lisVisible.length) return;
  1326. } else {
  1327. if ($lisVisible.filter('.selected').length === 0) return;
  1328. }
  1329. $lisVisible.toggleClass('selected', status);
  1330. for (var i = 0; i < lisVisLen; i++) {
  1331. var origIndex = $lisVisible[i].getAttribute('data-original-index');
  1332. selectedOptions[selectedOptions.length] = $options.eq(origIndex)[0];
  1333. }
  1334. $(selectedOptions).prop('selected', status);
  1335. this.render(false);
  1336. this.togglePlaceholder();
  1337. this.$element
  1338. .triggerNative('change');
  1339. },
  1340. selectAll: function () {
  1341. return this.changeAll(true);
  1342. },
  1343. deselectAll: function () {
  1344. return this.changeAll(false);
  1345. },
  1346. toggle: function (e) {
  1347. e = e || window.event;
  1348. if (e) e.stopPropagation();
  1349. this.$button.trigger('click');
  1350. },
  1351. keydown: function (e) {
  1352. var $this = $(this),
  1353. $parent = $this.is('input') ? $this.parent().parent() : $this.parent(),
  1354. $items,
  1355. that = $parent.data('this'),
  1356. index,
  1357. next,
  1358. first,
  1359. last,
  1360. prev,
  1361. nextPrev,
  1362. prevIndex,
  1363. isActive,
  1364. selector = ':not(.disabled, .hidden, .dropdown-header, .divider)',
  1365. keyCodeMap = {
  1366. 32: ' ',
  1367. 48: '0',
  1368. 49: '1',
  1369. 50: '2',
  1370. 51: '3',
  1371. 52: '4',
  1372. 53: '5',
  1373. 54: '6',
  1374. 55: '7',
  1375. 56: '8',
  1376. 57: '9',
  1377. 59: ';',
  1378. 65: 'a',
  1379. 66: 'b',
  1380. 67: 'c',
  1381. 68: 'd',
  1382. 69: 'e',
  1383. 70: 'f',
  1384. 71: 'g',
  1385. 72: 'h',
  1386. 73: 'i',
  1387. 74: 'j',
  1388. 75: 'k',
  1389. 76: 'l',
  1390. 77: 'm',
  1391. 78: 'n',
  1392. 79: 'o',
  1393. 80: 'p',
  1394. 81: 'q',
  1395. 82: 'r',
  1396. 83: 's',
  1397. 84: 't',
  1398. 85: 'u',
  1399. 86: 'v',
  1400. 87: 'w',
  1401. 88: 'x',
  1402. 89: 'y',
  1403. 90: 'z',
  1404. 96: '0',
  1405. 97: '1',
  1406. 98: '2',
  1407. 99: '3',
  1408. 100: '4',
  1409. 101: '5',
  1410. 102: '6',
  1411. 103: '7',
  1412. 104: '8',
  1413. 105: '9'
  1414. };
  1415. if (that.options.liveSearch) $parent = $this.parent().parent();
  1416. if (that.options.container) $parent = that.$menu;
  1417. $items = $('[role="listbox"] li', $parent);
  1418. isActive = that.$newElement.hasClass('open');
  1419. if (!isActive && (e.keyCode >= 48 && e.keyCode <= 57 || e.keyCode >= 96 && e.keyCode <= 105 || e.keyCode >= 65 && e.keyCode <= 90)) {
  1420. if (!that.options.container) {
  1421. that.setSize();
  1422. that.$menu.parent().addClass('open');
  1423. isActive = true;
  1424. } else {
  1425. that.$button.trigger('click');
  1426. }
  1427. that.$searchbox.focus();
  1428. return;
  1429. }
  1430. if (that.options.liveSearch) {
  1431. if (/(^9$|27)/.test(e.keyCode.toString(10)) && isActive) {
  1432. e.preventDefault();
  1433. e.stopPropagation();
  1434. that.$menuInner.click();
  1435. that.$button.focus();
  1436. }
  1437. // $items contains li elements when liveSearch is enabled
  1438. $items = $('[role="listbox"] li' + selector, $parent);
  1439. if (!$this.val() && !/(38|40)/.test(e.keyCode.toString(10))) {
  1440. if ($items.filter('.active').length === 0) {
  1441. $items = that.$menuInner.find('li');
  1442. if (that.options.liveSearchNormalize) {
  1443. $items = $items.filter(':a' + that._searchStyle() + '(' + normalizeToBase(keyCodeMap[e.keyCode]) + ')');
  1444. } else {
  1445. $items = $items.filter(':' + that._searchStyle() + '(' + keyCodeMap[e.keyCode] + ')');
  1446. }
  1447. }
  1448. }
  1449. }
  1450. if (!$items.length) return;
  1451. if (/(38|40)/.test(e.keyCode.toString(10))) {
  1452. index = $items.index($items.find('a').filter(':focus').parent());
  1453. first = $items.filter(selector).first().index();
  1454. last = $items.filter(selector).last().index();
  1455. next = $items.eq(index).nextAll(selector).eq(0).index();
  1456. prev = $items.eq(index).prevAll(selector).eq(0).index();
  1457. nextPrev = $items.eq(next).prevAll(selector).eq(0).index();
  1458. if (that.options.liveSearch) {
  1459. $items.each(function (i) {
  1460. if (!$(this).hasClass('disabled')) {
  1461. $(this).data('index', i);
  1462. }
  1463. });
  1464. index = $items.index($items.filter('.active'));
  1465. first = $items.first().data('index');
  1466. last = $items.last().data('index');
  1467. next = $items.eq(index).nextAll().eq(0).data('index');
  1468. prev = $items.eq(index).prevAll().eq(0).data('index');
  1469. nextPrev = $items.eq(next).prevAll().eq(0).data('index');
  1470. }
  1471. prevIndex = $this.data('prevIndex');
  1472. if (e.keyCode == 38) {
  1473. if (that.options.liveSearch) index--;
  1474. if (index != nextPrev && index > prev) index = prev;
  1475. if (index < first) index = first;
  1476. if (index == prevIndex) index = last;
  1477. } else if (e.keyCode == 40) {
  1478. if (that.options.liveSearch) index++;
  1479. if (index == -1) index = 0;
  1480. if (index != nextPrev && index < next) index = next;
  1481. if (index > last) index = last;
  1482. if (index == prevIndex) index = first;
  1483. }
  1484. $this.data('prevIndex', index);
  1485. if (!that.options.liveSearch) {
  1486. $items.eq(index).children('a').focus();
  1487. } else {
  1488. e.preventDefault();
  1489. if (!$this.hasClass('dropdown-toggle')) {
  1490. $items.removeClass('active').eq(index).addClass('active').children('a').focus();
  1491. $this.focus();
  1492. }
  1493. }
  1494. } else if (!$this.is('input')) {
  1495. var keyIndex = [],
  1496. count,
  1497. prevKey;
  1498. $items.each(function () {
  1499. if (!$(this).hasClass('disabled')) {
  1500. if ($.trim($(this).children('a').text().toLowerCase()).substring(0, 1) == keyCodeMap[e.keyCode]) {
  1501. keyIndex.push($(this).index());
  1502. }
  1503. }
  1504. });
  1505. count = $(document).data('keycount');
  1506. count++;
  1507. $(document).data('keycount', count);
  1508. prevKey = $.trim($(':focus').text().toLowerCase()).substring(0, 1);
  1509. if (prevKey != keyCodeMap[e.keyCode]) {
  1510. count = 1;
  1511. $(document).data('keycount', count);
  1512. } else if (count >= keyIndex.length) {
  1513. $(document).data('keycount', 0);
  1514. if (count > keyIndex.length) count = 1;
  1515. }
  1516. $items.eq(keyIndex[count - 1]).children('a').focus();
  1517. }
  1518. // Select focused option if "Enter", "Spacebar" or "Tab" (when selectOnTab is true) are pressed inside the menu.
  1519. if ((/(13|32)/.test(e.keyCode.toString(10)) || (/(^9$)/.test(e.keyCode.toString(10)) && that.options.selectOnTab)) && isActive) {
  1520. if (!/(32)/.test(e.keyCode.toString(10))) e.preventDefault();
  1521. if (!that.options.liveSearch) {
  1522. var elem = $(':focus');
  1523. elem.click();
  1524. // Bring back focus for multiselects
  1525. elem.focus();
  1526. // Prevent screen from scrolling if the user hit the spacebar
  1527. e.preventDefault();
  1528. // Fixes spacebar selection of dropdown items in FF & IE
  1529. $(document).data('spaceSelect', true);
  1530. } else if (!/(32)/.test(e.keyCode.toString(10))) {
  1531. that.$menuInner.find('.active a').click();
  1532. $this.focus();
  1533. }
  1534. $(document).data('keycount', 0);
  1535. }
  1536. if ((/(^9$|27)/.test(e.keyCode.toString(10)) && isActive && (that.multiple || that.options.liveSearch)) || (/(27)/.test(e.keyCode.toString(10)) && !isActive)) {
  1537. that.$menu.parent().removeClass('open');
  1538. if (that.options.container) that.$newElement.removeClass('open');
  1539. that.$button.focus();
  1540. }
  1541. },
  1542. mobile: function () {
  1543. this.$element.addClass('mobile-device');
  1544. },
  1545. refresh: function () {
  1546. this.$lis = null;
  1547. this.liObj = {};
  1548. this.reloadLi();
  1549. this.render();
  1550. this.checkDisabled();
  1551. this.liHeight(true);
  1552. this.setStyle();
  1553. this.setWidth();
  1554. if (this.$lis) this.$searchbox.trigger('propertychange');
  1555. this.$element.trigger('refreshed.bs.select');
  1556. },
  1557. hide: function () {
  1558. this.$newElement.hide();
  1559. },
  1560. show: function () {
  1561. this.$newElement.show();
  1562. },
  1563. remove: function () {
  1564. this.$newElement.remove();
  1565. this.$element.remove();
  1566. },
  1567. destroy: function () {
  1568. this.$newElement.before(this.$element).remove();
  1569. if (this.$bsContainer) {
  1570. this.$bsContainer.remove();
  1571. } else {
  1572. this.$menu.remove();
  1573. }
  1574. this.$element
  1575. .off('.bs.select')
  1576. .removeData('selectpicker')
  1577. .removeClass('bs-select-hidden selectpicker');
  1578. }
  1579. };
  1580. // SELECTPICKER PLUGIN DEFINITION
  1581. // ==============================
  1582. function Plugin(option) {
  1583. // get the args of the outer function..
  1584. var args = arguments;
  1585. // The arguments of the function are explicitly re-defined from the argument list, because the shift causes them
  1586. // to get lost/corrupted in android 2.3 and IE9 #715 #775
  1587. var _option = option;
  1588. [].shift.apply(args);
  1589. var value;
  1590. var chain = this.each(function () {
  1591. var $this = $(this);
  1592. if ($this.is('select')) {
  1593. var data = $this.data('selectpicker'),
  1594. options = typeof _option == 'object' && _option;
  1595. if (!data) {
  1596. var config = $.extend({}, Selectpicker.DEFAULTS, $.fn.selectpicker.defaults || {}, $this.data(), options);
  1597. config.template = $.extend({}, Selectpicker.DEFAULTS.template, ($.fn.selectpicker.defaults ? $.fn.selectpicker.defaults.template : {}), $this.data().template, options.template);
  1598. $this.data('selectpicker', (data = new Selectpicker(this, config)));
  1599. } else if (options) {
  1600. for (var i in options) {
  1601. if (options.hasOwnProperty(i)) {
  1602. data.options[i] = options[i];
  1603. }
  1604. }
  1605. }
  1606. if (typeof _option == 'string') {
  1607. if (data[_option] instanceof Function) {
  1608. value = data[_option].apply(data, args);
  1609. } else {
  1610. value = data.options[_option];
  1611. }
  1612. }
  1613. }
  1614. });
  1615. if (typeof value !== 'undefined') {
  1616. //noinspection JSUnusedAssignment
  1617. return value;
  1618. } else {
  1619. return chain;
  1620. }
  1621. }
  1622. var old = $.fn.selectpicker;
  1623. $.fn.selectpicker = Plugin;
  1624. $.fn.selectpicker.Constructor = Selectpicker;
  1625. // SELECTPICKER NO CONFLICT
  1626. // ========================
  1627. $.fn.selectpicker.noConflict = function () {
  1628. $.fn.selectpicker = old;
  1629. return this;
  1630. };
  1631. $(document)
  1632. .data('keycount', 0)
  1633. .on('keydown.bs.select', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role="listbox"], .bs-searchbox input', Selectpicker.prototype.keydown)
  1634. .on('focusin.modal', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role="listbox"], .bs-searchbox input', function (e) {
  1635. e.stopPropagation();
  1636. });
  1637. // SELECTPICKER DATA-API
  1638. // =====================
  1639. $(window).on('load.bs.select.data-api', function () {
  1640. $('.selectpicker').each(function () {
  1641. var $selectpicker = $(this);
  1642. Plugin.call($selectpicker, $selectpicker.data());
  1643. })
  1644. });
  1645. })(jQuery);
  1646. }));