bootstrap-select.js 67 KB

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