bootstrap-select.js 67 KB

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