bootstrap-select.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. /*!
  2. * Bootstrap-select v1.6.3 (http://silviomoreto.github.io/bootstrap-select/)
  3. *
  4. * Copyright 2013-2014 bootstrap-select
  5. * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
  6. */
  7. (function ($) {
  8. 'use strict';
  9. // Case insensitive search
  10. $.expr[':'].icontains = function (obj, index, meta) {
  11. return icontains($(obj).text(), meta[3]);
  12. };
  13. // Case and accent insensitive search
  14. $.expr[':'].aicontains = function (obj, index, meta) {
  15. return icontains($(obj).data('normalizedText') || $(obj).text(), meta[3]);
  16. };
  17. /**
  18. * Actual implementation of the case insensitive search.
  19. * @access private
  20. * @param {String} haystack
  21. * @param {String} needle
  22. * @returns {boolean}
  23. */
  24. function icontains(haystack, needle) {
  25. return haystack.toUpperCase().indexOf(needle.toUpperCase()) > -1;
  26. }
  27. /**
  28. * Remove all diatrics from the given text.
  29. * @access private
  30. * @param {String} text
  31. * @returns {String}
  32. */
  33. function normalizeToBase(text) {
  34. var rExps = [
  35. {re: /[\xC0-\xC6]/g, ch: "A"},
  36. {re: /[\xE0-\xE6]/g, ch: "a"},
  37. {re: /[\xC8-\xCB]/g, ch: "E"},
  38. {re: /[\xE8-\xEB]/g, ch: "e"},
  39. {re: /[\xCC-\xCF]/g, ch: "I"},
  40. {re: /[\xEC-\xEF]/g, ch: "i"},
  41. {re: /[\xD2-\xD6]/g, ch: "O"},
  42. {re: /[\xF2-\xF6]/g, ch: "o"},
  43. {re: /[\xD9-\xDC]/g, ch: "U"},
  44. {re: /[\xF9-\xFC]/g, ch: "u"},
  45. {re: /[\xC7-\xE7]/g, ch: "c"},
  46. {re: /[\xD1]/g, ch: "N"},
  47. {re: /[\xF1]/g, ch: "n"}
  48. ];
  49. $.each(rExps, function () {
  50. text = text.replace(this.re, this.ch);
  51. });
  52. return text;
  53. }
  54. function htmlEscape(html) {
  55. var escapeMap = {
  56. '&': '&',
  57. '<': '&lt;',
  58. '>': '&gt;',
  59. '"': '&quot;',
  60. "'": '&#x27;',
  61. '`': '&#x60;'
  62. };
  63. var source = '(?:' + Object.keys(escapeMap).join('|') + ')',
  64. testRegexp = new RegExp(source),
  65. replaceRegexp = new RegExp(source, 'g'),
  66. string = html == null ? '' : '' + html;
  67. return testRegexp.test(string) ? string.replace(replaceRegexp, function (match) {
  68. return escapeMap[match];
  69. }) : string;
  70. }
  71. var Selectpicker = function (element, options, e) {
  72. if (e) {
  73. e.stopPropagation();
  74. e.preventDefault();
  75. }
  76. this.$element = $(element);
  77. this.$newElement = null;
  78. this.$button = null;
  79. this.$menu = null;
  80. this.$lis = null;
  81. this.options = options;
  82. // 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
  83. // data-attribute)
  84. if (this.options.title === null) {
  85. this.options.title = this.$element.attr('title');
  86. }
  87. //Expose public methods
  88. this.val = Selectpicker.prototype.val;
  89. this.render = Selectpicker.prototype.render;
  90. this.refresh = Selectpicker.prototype.refresh;
  91. this.setStyle = Selectpicker.prototype.setStyle;
  92. this.selectAll = Selectpicker.prototype.selectAll;
  93. this.deselectAll = Selectpicker.prototype.deselectAll;
  94. this.destroy = Selectpicker.prototype.remove;
  95. this.remove = Selectpicker.prototype.remove;
  96. this.show = Selectpicker.prototype.show;
  97. this.hide = Selectpicker.prototype.hide;
  98. this.init();
  99. };
  100. Selectpicker.VERSION = '1.6.3';
  101. // part of this is duplicated in i18n/defaults-en_US.js. Make sure to update both.
  102. Selectpicker.DEFAULTS = {
  103. noneSelectedText: 'Nothing selected',
  104. noneResultsText: 'No results match',
  105. countSelectedText: function (numSelected, numTotal) {
  106. return (numSelected == 1) ? "{0} item selected" : "{0} items selected";
  107. },
  108. maxOptionsText: function (numAll, numGroup) {
  109. var arr = [];
  110. arr[0] = (numAll == 1) ? 'Limit reached ({n} item max)' : 'Limit reached ({n} items max)';
  111. arr[1] = (numGroup == 1) ? 'Group limit reached ({n} item max)' : 'Group limit reached ({n} items max)';
  112. return arr;
  113. },
  114. selectAllText: 'Select All',
  115. deselectAllText: 'Deselect All',
  116. multipleSeparator: ', ',
  117. style: 'btn-default',
  118. size: 'auto',
  119. title: null,
  120. selectedTextFormat: 'values',
  121. width: false,
  122. container: false,
  123. hideDisabled: false,
  124. showSubtext: false,
  125. showIcon: true,
  126. showContent: true,
  127. dropupAuto: true,
  128. header: false,
  129. liveSearch: false,
  130. actionsBox: false,
  131. iconBase: 'glyphicon',
  132. tickIcon: 'glyphicon-ok',
  133. maxOptions: false,
  134. mobile: false,
  135. selectOnTab: false,
  136. dropdownAlignRight: false,
  137. searchAccentInsensitive: false
  138. };
  139. Selectpicker.prototype = {
  140. constructor: Selectpicker,
  141. init: function () {
  142. var that = this,
  143. id = this.$element.attr('id');
  144. this.$element.hide();
  145. this.multiple = this.$element.prop('multiple');
  146. this.autofocus = this.$element.prop('autofocus');
  147. this.$newElement = this.createView();
  148. this.$element.after(this.$newElement);
  149. this.$menu = this.$newElement.find('> .dropdown-menu');
  150. this.$button = this.$newElement.find('> button');
  151. this.$searchbox = this.$newElement.find('input');
  152. if (this.options.dropdownAlignRight)
  153. this.$menu.addClass('dropdown-menu-right');
  154. if (typeof id !== 'undefined') {
  155. this.$button.attr('data-id', id);
  156. $('label[for="' + id + '"]').click(function (e) {
  157. e.preventDefault();
  158. that.$button.focus();
  159. });
  160. }
  161. this.checkDisabled();
  162. this.clickListener();
  163. if (this.options.liveSearch) this.liveSearchListener();
  164. this.render();
  165. this.liHeight();
  166. this.setStyle();
  167. this.setWidth();
  168. if (this.options.container) this.selectPosition();
  169. this.$menu.data('this', this);
  170. this.$newElement.data('this', this);
  171. if (this.options.mobile) this.mobile();
  172. },
  173. createDropdown: function () {
  174. // Options
  175. // If we are multiple, then add the show-tick class by default
  176. var multiple = this.multiple ? ' show-tick' : '',
  177. inputGroup = this.$element.parent().hasClass('input-group') ? ' input-group-btn' : '',
  178. autofocus = this.autofocus ? ' autofocus' : '',
  179. btnSize = this.$element.parents().hasClass('form-group-lg') ? ' btn-lg' : (this.$element.parents().hasClass('form-group-sm') ? ' btn-sm' : '');
  180. // Elements
  181. var header = this.options.header ? '<div class="popover-title"><button type="button" class="close" aria-hidden="true">&times;</button>' + this.options.header + '</div>' : '';
  182. var searchbox = this.options.liveSearch ? '<div class="bs-searchbox"><input type="text" class="input-block-level form-control" autocomplete="off" /></div>' : '';
  183. var actionsbox = this.options.actionsBox ? '<div class="bs-actionsbox">' +
  184. '<div class="btn-group btn-block">' +
  185. '<button class="actions-btn bs-select-all btn btn-sm btn-default">' +
  186. this.options.selectAllText +
  187. '</button>' +
  188. '<button class="actions-btn bs-deselect-all btn btn-sm btn-default">' +
  189. this.options.deselectAllText +
  190. '</button>' +
  191. '</div>' +
  192. '</div>' : '';
  193. var drop =
  194. '<div class="btn-group bootstrap-select' + multiple + inputGroup + '">' +
  195. '<button type="button" class="btn dropdown-toggle selectpicker' + btnSize + '" data-toggle="dropdown"' + autofocus + '>' +
  196. '<span class="filter-option pull-left"></span>&nbsp;' +
  197. '<span class="caret"></span>' +
  198. '</button>' +
  199. '<div class="dropdown-menu open">' +
  200. header +
  201. searchbox +
  202. actionsbox +
  203. '<ul class="dropdown-menu inner selectpicker" role="menu">' +
  204. '</ul>' +
  205. '</div>' +
  206. '</div>';
  207. return $(drop);
  208. },
  209. createView: function () {
  210. var $drop = this.createDropdown();
  211. var $li = this.createLi();
  212. $drop.find('ul').append($li);
  213. return $drop;
  214. },
  215. reloadLi: function () {
  216. //Remove all children.
  217. this.destroyLi();
  218. //Re build
  219. var $li = this.createLi();
  220. this.$menu.find('ul').append($li);
  221. },
  222. destroyLi: function () {
  223. this.$menu.find('li').remove();
  224. },
  225. createLi: function () {
  226. var that = this,
  227. _li = [],
  228. optID = 0;
  229. // Helper functions
  230. /**
  231. * @param content
  232. * @param [index]
  233. * @param [classes]
  234. * @returns {string}
  235. */
  236. var generateLI = function (content, index, classes) {
  237. return '<li' +
  238. (typeof classes !== 'undefined' ? ' class="' + classes + '"' : '') +
  239. (typeof index !== 'undefined' | null === index ? ' data-original-index="' + index + '"' : '') +
  240. '>' + content + '</li>';
  241. };
  242. /**
  243. * @param text
  244. * @param [classes]
  245. * @param [inline]
  246. * @param [optgroup]
  247. * @returns {string}
  248. */
  249. var generateA = function (text, classes, inline, optgroup) {
  250. var normText = normalizeToBase(htmlEscape(text));
  251. return '<a tabindex="0"' +
  252. (typeof classes !== 'undefined' ? ' class="' + classes + '"' : '') +
  253. (typeof inline !== 'undefined' ? ' style="' + inline + '"' : '') +
  254. (typeof optgroup !== 'undefined' ? 'data-optgroup="' + optgroup + '"' : '') +
  255. ' data-normalized-text="' + normText + '"' +
  256. '>' + text +
  257. '<span class="' + that.options.iconBase + ' ' + that.options.tickIcon + ' check-mark"></span>' +
  258. '</a>';
  259. };
  260. this.$element.find('option').each(function () {
  261. var $this = $(this);
  262. // Get the class and text for the option
  263. var optionClass = $this.attr('class') || '',
  264. inline = $this.attr('style'),
  265. text = $this.data('content') ? $this.data('content') : $this.html(),
  266. subtext = typeof $this.data('subtext') !== 'undefined' ? '<small class="muted text-muted">' + $this.data('subtext') + '</small>' : '',
  267. icon = typeof $this.data('icon') !== 'undefined' ? '<span class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></span> ' : '',
  268. isDisabled = $this.is(':disabled') || $this.parent().is(':disabled'),
  269. index = $this[0].index;
  270. if (icon !== '' && isDisabled) {
  271. icon = '<span>' + icon + '</span>';
  272. }
  273. if (!$this.data('content')) {
  274. // Prepend any icon and append any subtext to the main text.
  275. text = icon + '<span class="text">' + text + subtext + '</span>';
  276. }
  277. if (that.options.hideDisabled && isDisabled) {
  278. return;
  279. }
  280. if ($this.parent().is('optgroup') && $this.data('divider') !== true) {
  281. if ($this.index() === 0) { // Is it the first option of the optgroup?
  282. optID += 1;
  283. // Get the opt group label
  284. var label = $this.parent().attr('label');
  285. var labelSubtext = typeof $this.parent().data('subtext') !== 'undefined' ? '<small class="muted text-muted">' + $this.parent().data('subtext') + '</small>' : '';
  286. var labelIcon = $this.parent().data('icon') ? '<span class="' + that.options.iconBase + ' ' + $this.parent().data('icon') + '"></span> ' : '';
  287. label = labelIcon + '<span class="text">' + label + labelSubtext + '</span>';
  288. if (index !== 0 && _li.length > 0) { // Is it NOT the first option of the select && are there elements in the dropdown?
  289. _li.push(generateLI('', null, 'divider'));
  290. }
  291. _li.push(generateLI(label, null, 'dropdown-header'));
  292. }
  293. _li.push(generateLI(generateA(text, 'opt ' + optionClass, inline, optID), index));
  294. } else if ($this.data('divider') === true) {
  295. _li.push(generateLI('', index, 'divider'));
  296. } else if ($this.data('hidden') === true) {
  297. _li.push(generateLI(generateA(text, optionClass, inline), index, 'hide is-hidden'));
  298. } else {
  299. _li.push(generateLI(generateA(text, optionClass, inline), index));
  300. }
  301. });
  302. //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
  303. if (!this.multiple && this.$element.find('option:selected').length === 0 && !this.options.title) {
  304. this.$element.find('option').eq(0).prop('selected', true).attr('selected', 'selected');
  305. }
  306. return $(_li.join(''));
  307. },
  308. findLis: function () {
  309. if (this.$lis == null) this.$lis = this.$menu.find('li');
  310. return this.$lis;
  311. },
  312. /**
  313. * @param [updateLi] defaults to true
  314. */
  315. render: function (updateLi) {
  316. var that = this;
  317. //Update the LI to match the SELECT
  318. if (updateLi !== false) {
  319. this.$element.find('option').each(function (index) {
  320. that.setDisabled(index, $(this).is(':disabled') || $(this).parent().is(':disabled'));
  321. that.setSelected(index, $(this).is(':selected'));
  322. });
  323. }
  324. this.tabIndex();
  325. var notDisabled = this.options.hideDisabled ? ':not([disabled])' : '';
  326. var selectedItems = this.$element.find('option:selected' + notDisabled).map(function () {
  327. var $this = $(this);
  328. var icon = $this.data('icon') && that.options.showIcon ? '<i class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></i> ' : '';
  329. var subtext;
  330. if (that.options.showSubtext && $this.attr('data-subtext') && !that.multiple) {
  331. subtext = ' <small class="muted text-muted">' + $this.data('subtext') + '</small>';
  332. } else {
  333. subtext = '';
  334. }
  335. if ($this.data('content') && that.options.showContent) {
  336. return $this.data('content');
  337. } else if (typeof $this.attr('title') !== 'undefined') {
  338. return $this.attr('title');
  339. } else {
  340. return icon + $this.html() + subtext;
  341. }
  342. }).toArray();
  343. //Fixes issue in IE10 occurring when no default option is selected and at least one option is disabled
  344. //Convert all the values into a comma delimited string
  345. var title = !this.multiple ? selectedItems[0] : selectedItems.join(this.options.multipleSeparator);
  346. //If this is multi select, and the selectText type is count, the show 1 of 2 selected etc..
  347. if (this.multiple && this.options.selectedTextFormat.indexOf('count') > -1) {
  348. var max = this.options.selectedTextFormat.split('>');
  349. if ((max.length > 1 && selectedItems.length > max[1]) || (max.length == 1 && selectedItems.length >= 2)) {
  350. notDisabled = this.options.hideDisabled ? ', [disabled]' : '';
  351. var totalCount = this.$element.find('option').not('[data-divider="true"], [data-hidden="true"]' + notDisabled).length,
  352. tr8nText = (typeof this.options.countSelectedText === 'function') ? this.options.countSelectedText(selectedItems.length, totalCount) : this.options.countSelectedText;
  353. title = tr8nText.replace('{0}', selectedItems.length.toString()).replace('{1}', totalCount.toString());
  354. }
  355. }
  356. this.options.title = this.$element.attr('title');
  357. if (this.options.selectedTextFormat == 'static') {
  358. title = this.options.title;
  359. }
  360. //If we dont have a title, then use the default, or if nothing is set at all, use the not selected text
  361. if (!title) {
  362. title = typeof this.options.title !== 'undefined' ? this.options.title : this.options.noneSelectedText;
  363. }
  364. this.$button.attr('title', htmlEscape(title));
  365. this.$newElement.find('.filter-option').html(title);
  366. },
  367. /**
  368. * @param [style]
  369. * @param [status]
  370. */
  371. setStyle: function (style, status) {
  372. if (this.$element.attr('class')) {
  373. this.$newElement.addClass(this.$element.attr('class').replace(/selectpicker|mobile-device|validate\[.*\]/gi, ''));
  374. }
  375. var buttonClass = style ? style : this.options.style;
  376. if (status == 'add') {
  377. this.$button.addClass(buttonClass);
  378. } else if (status == 'remove') {
  379. this.$button.removeClass(buttonClass);
  380. } else {
  381. this.$button.removeClass(this.options.style);
  382. this.$button.addClass(buttonClass);
  383. }
  384. },
  385. liHeight: function () {
  386. if (this.options.size === false) return;
  387. var $selectClone = this.$menu.parent().clone().find('> .dropdown-toggle').prop('autofocus', false).end().appendTo('body'),
  388. $menuClone = $selectClone.addClass('open').find('> .dropdown-menu'),
  389. liHeight = $menuClone.find('li').not('.divider').not('.dropdown-header').filter(':visible').children('a').outerHeight(),
  390. headerHeight = this.options.header ? $menuClone.find('.popover-title').outerHeight() : 0,
  391. searchHeight = this.options.liveSearch ? $menuClone.find('.bs-searchbox').outerHeight() : 0,
  392. actionsHeight = this.options.actionsBox ? $menuClone.find('.bs-actionsbox').outerHeight() : 0;
  393. $selectClone.remove();
  394. this.$newElement
  395. .data('liHeight', liHeight)
  396. .data('headerHeight', headerHeight)
  397. .data('searchHeight', searchHeight)
  398. .data('actionsHeight', actionsHeight);
  399. },
  400. setSize: function () {
  401. this.findLis();
  402. var that = this,
  403. menu = this.$menu,
  404. menuInner = menu.find('.inner'),
  405. selectHeight = this.$newElement.outerHeight(),
  406. liHeight = this.$newElement.data('liHeight'),
  407. headerHeight = this.$newElement.data('headerHeight'),
  408. searchHeight = this.$newElement.data('searchHeight'),
  409. actionsHeight = this.$newElement.data('actionsHeight'),
  410. divHeight = this.$lis.filter('.divider').outerHeight(true),
  411. menuPadding = parseInt(menu.css('padding-top')) +
  412. parseInt(menu.css('padding-bottom')) +
  413. parseInt(menu.css('border-top-width')) +
  414. parseInt(menu.css('border-bottom-width')),
  415. notDisabled = this.options.hideDisabled ? ', .disabled' : '',
  416. $window = $(window),
  417. menuExtras = menuPadding + parseInt(menu.css('margin-top')) + parseInt(menu.css('margin-bottom')) + 2,
  418. menuHeight,
  419. selectOffsetTop,
  420. selectOffsetBot,
  421. posVert = function () {
  422. // JQuery defines a scrollTop function, but in pure JS it's a property
  423. //noinspection JSValidateTypes
  424. selectOffsetTop = that.$newElement.offset().top - $window.scrollTop();
  425. selectOffsetBot = $window.height() - selectOffsetTop - selectHeight;
  426. };
  427. posVert();
  428. if (this.options.header) menu.css('padding-top', 0);
  429. if (this.options.size == 'auto') {
  430. var getSize = function () {
  431. var minHeight,
  432. lisVis = that.$lis.not('.hide');
  433. posVert();
  434. menuHeight = selectOffsetBot - menuExtras;
  435. if (that.options.dropupAuto) {
  436. that.$newElement.toggleClass('dropup', (selectOffsetTop > selectOffsetBot) && ((menuHeight - menuExtras) < menu.height()));
  437. }
  438. if (that.$newElement.hasClass('dropup')) {
  439. menuHeight = selectOffsetTop - menuExtras;
  440. }
  441. if ((lisVis.length + lisVis.filter('.dropdown-header').length) > 3) {
  442. minHeight = liHeight * 3 + menuExtras - 2;
  443. } else {
  444. minHeight = 0;
  445. }
  446. menu.css({
  447. 'max-height': menuHeight + 'px',
  448. 'overflow': 'hidden',
  449. 'min-height': minHeight + headerHeight + searchHeight + actionsHeight + 'px'
  450. });
  451. menuInner.css({
  452. 'max-height': menuHeight - headerHeight - searchHeight - actionsHeight - menuPadding + 'px',
  453. 'overflow-y': 'auto',
  454. 'min-height': Math.max(minHeight - menuPadding, 0) + 'px'
  455. });
  456. };
  457. getSize();
  458. this.$searchbox.off('input.getSize propertychange.getSize').on('input.getSize propertychange.getSize', getSize);
  459. $(window).off('resize.getSize').on('resize.getSize', getSize);
  460. $(window).off('scroll.getSize').on('scroll.getSize', getSize);
  461. } else if (this.options.size && this.options.size != 'auto' && menu.find('li' + notDisabled).length > this.options.size) {
  462. var optIndex = this.$lis.not('.divider' + notDisabled).find(' > *').slice(0, this.options.size).last().parent().index();
  463. var divLength = this.$lis.slice(0, optIndex + 1).filter('.divider').length;
  464. menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding;
  465. if (that.options.dropupAuto) {
  466. //noinspection JSUnusedAssignment
  467. this.$newElement.toggleClass('dropup', (selectOffsetTop > selectOffsetBot) && (menuHeight < menu.height()));
  468. }
  469. menu.css({'max-height': menuHeight + headerHeight + searchHeight + actionsHeight + 'px', 'overflow': 'hidden'});
  470. menuInner.css({'max-height': menuHeight - menuPadding + 'px', 'overflow-y': 'auto'});
  471. }
  472. },
  473. setWidth: function () {
  474. if (this.options.width == 'auto') {
  475. this.$menu.css('min-width', '0');
  476. // Get correct width if element hidden
  477. var selectClone = this.$newElement.clone().appendTo('body');
  478. var ulWidth = selectClone.find('> .dropdown-menu').css('width');
  479. var btnWidth = selectClone.css('width', 'auto').find('> button').css('width');
  480. selectClone.remove();
  481. // Set width to whatever's larger, button title or longest option
  482. this.$newElement.css('width', Math.max(parseInt(ulWidth), parseInt(btnWidth)) + 'px');
  483. } else if (this.options.width == 'fit') {
  484. // Remove inline min-width so width can be changed from 'auto'
  485. this.$menu.css('min-width', '');
  486. this.$newElement.css('width', '').addClass('fit-width');
  487. } else if (this.options.width) {
  488. // Remove inline min-width so width can be changed from 'auto'
  489. this.$menu.css('min-width', '');
  490. this.$newElement.css('width', this.options.width);
  491. } else {
  492. // Remove inline min-width/width so width can be changed
  493. this.$menu.css('min-width', '');
  494. this.$newElement.css('width', '');
  495. }
  496. // Remove fit-width class if width is changed programmatically
  497. if (this.$newElement.hasClass('fit-width') && this.options.width !== 'fit') {
  498. this.$newElement.removeClass('fit-width');
  499. }
  500. },
  501. selectPosition: function () {
  502. var that = this,
  503. drop = '<div />',
  504. $drop = $(drop),
  505. pos,
  506. actualHeight,
  507. getPlacement = function ($element) {
  508. $drop.addClass($element.attr('class').replace(/form-control/gi, '')).toggleClass('dropup', $element.hasClass('dropup'));
  509. pos = $element.offset();
  510. actualHeight = $element.hasClass('dropup') ? 0 : $element[0].offsetHeight;
  511. $drop.css({
  512. 'top': pos.top + actualHeight,
  513. 'left': pos.left,
  514. 'width': $element[0].offsetWidth,
  515. 'position': 'absolute'
  516. });
  517. };
  518. this.$newElement.on('click', function () {
  519. if (that.isDisabled()) {
  520. return;
  521. }
  522. getPlacement($(this));
  523. $drop.appendTo(that.options.container);
  524. $drop.toggleClass('open', !$(this).hasClass('open'));
  525. $drop.append(that.$menu);
  526. });
  527. $(window).resize(function () {
  528. getPlacement(that.$newElement);
  529. });
  530. $(window).on('scroll', function () {
  531. getPlacement(that.$newElement);
  532. });
  533. $('html').on('click', function (e) {
  534. if ($(e.target).closest(that.$newElement).length < 1) {
  535. $drop.removeClass('open');
  536. }
  537. });
  538. },
  539. setSelected: function (index, selected) {
  540. this.findLis();
  541. this.$lis.filter('[data-original-index="' + index + '"]').toggleClass('selected', selected);
  542. },
  543. setDisabled: function (index, disabled) {
  544. this.findLis();
  545. if (disabled) {
  546. this.$lis.filter('[data-original-index="' + index + '"]').addClass('disabled').find('a').attr('href', '#').attr('tabindex', -1);
  547. } else {
  548. this.$lis.filter('[data-original-index="' + index + '"]').removeClass('disabled').find('a').removeAttr('href').attr('tabindex', 0);
  549. }
  550. },
  551. isDisabled: function () {
  552. return this.$element.is(':disabled');
  553. },
  554. checkDisabled: function () {
  555. var that = this;
  556. if (this.isDisabled()) {
  557. this.$button.addClass('disabled').attr('tabindex', -1);
  558. } else {
  559. if (this.$button.hasClass('disabled')) {
  560. this.$button.removeClass('disabled');
  561. }
  562. if (this.$button.attr('tabindex') == -1) {
  563. if (!this.$element.data('tabindex')) this.$button.removeAttr('tabindex');
  564. }
  565. }
  566. this.$button.click(function () {
  567. return !that.isDisabled();
  568. });
  569. },
  570. tabIndex: function () {
  571. if (this.$element.is('[tabindex]')) {
  572. this.$element.data('tabindex', this.$element.attr('tabindex'));
  573. this.$button.attr('tabindex', this.$element.data('tabindex'));
  574. }
  575. },
  576. clickListener: function () {
  577. var that = this;
  578. this.$newElement.on('touchstart.dropdown', '.dropdown-menu', function (e) {
  579. e.stopPropagation();
  580. });
  581. this.$newElement.on('click', function () {
  582. that.setSize();
  583. if (!that.options.liveSearch && !that.multiple) {
  584. setTimeout(function () {
  585. that.$menu.find('.selected a').focus();
  586. }, 10);
  587. }
  588. });
  589. this.$menu.on('click', 'li a', function (e) {
  590. var $this = $(this),
  591. clickedIndex = $this.parent().data('originalIndex'),
  592. prevValue = that.$element.val(),
  593. prevIndex = that.$element.prop('selectedIndex');
  594. // Don't close on multi choice menu
  595. if (that.multiple) {
  596. e.stopPropagation();
  597. }
  598. e.preventDefault();
  599. //Don't run if we have been disabled
  600. if (!that.isDisabled() && !$this.parent().hasClass('disabled')) {
  601. var $options = that.$element.find('option'),
  602. $option = $options.eq(clickedIndex),
  603. state = $option.prop('selected'),
  604. $optgroup = $option.parent('optgroup'),
  605. maxOptions = that.options.maxOptions,
  606. maxOptionsGrp = $optgroup.data('maxOptions') || false;
  607. if (!that.multiple) { // Deselect all others if not multi select box
  608. $options.prop('selected', false);
  609. $option.prop('selected', true);
  610. that.$menu.find('.selected').removeClass('selected');
  611. that.setSelected(clickedIndex, true);
  612. } else { // Toggle the one we have chosen if we are multi select.
  613. $option.prop('selected', !state);
  614. that.setSelected(clickedIndex, !state);
  615. $this.blur();
  616. if ((maxOptions !== false) || (maxOptionsGrp !== false)) {
  617. var maxReached = maxOptions < $options.filter(':selected').length,
  618. maxReachedGrp = maxOptionsGrp < $optgroup.find('option:selected').length;
  619. if ((maxOptions && maxReached) || (maxOptionsGrp && maxReachedGrp)) {
  620. if (maxOptions && maxOptions == 1) {
  621. $options.prop('selected', false);
  622. $option.prop('selected', true);
  623. that.$menu.find('.selected').removeClass('selected');
  624. that.setSelected(clickedIndex, true);
  625. } else if (maxOptionsGrp && maxOptionsGrp == 1) {
  626. $optgroup.find('option:selected').prop('selected', false);
  627. $option.prop('selected', true);
  628. var optgroupID = $this.data('optgroup');
  629. that.$menu.find('.selected').has('a[data-optgroup="' + optgroupID + '"]').removeClass('selected');
  630. that.setSelected(clickedIndex, true);
  631. } else {
  632. var maxOptionsArr = (typeof that.options.maxOptionsText === 'function') ?
  633. that.options.maxOptionsText(maxOptions, maxOptionsGrp) : that.options.maxOptionsText,
  634. maxTxt = maxOptionsArr[0].replace('{n}', maxOptions),
  635. maxTxtGrp = maxOptionsArr[1].replace('{n}', maxOptionsGrp),
  636. $notify = $('<div class="notify"></div>');
  637. // If {var} is set in array, replace it
  638. /** @deprecated */
  639. if (maxOptionsArr[2]) {
  640. maxTxt = maxTxt.replace('{var}', maxOptionsArr[2][maxOptions > 1 ? 0 : 1]);
  641. maxTxtGrp = maxTxtGrp.replace('{var}', maxOptionsArr[2][maxOptionsGrp > 1 ? 0 : 1]);
  642. }
  643. $option.prop('selected', false);
  644. that.$menu.append($notify);
  645. if (maxOptions && maxReached) {
  646. $notify.append($('<div>' + maxTxt + '</div>'));
  647. that.$element.trigger('maxReached.bs.select');
  648. }
  649. if (maxOptionsGrp && maxReachedGrp) {
  650. $notify.append($('<div>' + maxTxtGrp + '</div>'));
  651. that.$element.trigger('maxReachedGrp.bs.select');
  652. }
  653. setTimeout(function () {
  654. that.setSelected(clickedIndex, false);
  655. }, 10);
  656. $notify.delay(750).fadeOut(300, function () {
  657. $(this).remove();
  658. });
  659. }
  660. }
  661. }
  662. }
  663. if (!that.multiple) {
  664. that.$button.focus();
  665. } else if (that.options.liveSearch) {
  666. that.$searchbox.focus();
  667. }
  668. // Trigger select 'change'
  669. if ((prevValue != that.$element.val() && that.multiple) || (prevIndex != that.$element.prop('selectedIndex') && !that.multiple)) {
  670. that.$element.change();
  671. }
  672. }
  673. });
  674. this.$menu.on('click', 'li.disabled a, .popover-title, .popover-title :not(.close)', function (e) {
  675. if (e.target == this) {
  676. e.preventDefault();
  677. e.stopPropagation();
  678. if (!that.options.liveSearch) {
  679. that.$button.focus();
  680. } else {
  681. that.$searchbox.focus();
  682. }
  683. }
  684. });
  685. this.$menu.on('click', 'li.divider, li.dropdown-header', function (e) {
  686. e.preventDefault();
  687. e.stopPropagation();
  688. if (!that.options.liveSearch) {
  689. that.$button.focus();
  690. } else {
  691. that.$searchbox.focus();
  692. }
  693. });
  694. this.$menu.on('click', '.popover-title .close', function () {
  695. that.$button.focus();
  696. });
  697. this.$searchbox.on('click', function (e) {
  698. e.stopPropagation();
  699. });
  700. this.$menu.on('click', '.actions-btn', function (e) {
  701. if (that.options.liveSearch) {
  702. that.$searchbox.focus();
  703. } else {
  704. that.$button.focus();
  705. }
  706. e.preventDefault();
  707. e.stopPropagation();
  708. if ($(this).is('.bs-select-all')) {
  709. that.selectAll();
  710. } else {
  711. that.deselectAll();
  712. }
  713. that.$element.change();
  714. });
  715. this.$element.change(function () {
  716. that.render(false);
  717. });
  718. },
  719. liveSearchListener: function () {
  720. var that = this,
  721. no_results = $('<li class="no-results"></li>');
  722. this.$newElement.on('click.dropdown.data-api touchstart.dropdown.data-api', function () {
  723. that.$menu.find('.active').removeClass('active');
  724. if (!!that.$searchbox.val()) {
  725. that.$searchbox.val('');
  726. that.$lis.not('.is-hidden').removeClass('hide');
  727. if (!!no_results.parent().length) no_results.remove();
  728. }
  729. if (!that.multiple) that.$menu.find('.selected').addClass('active');
  730. setTimeout(function () {
  731. that.$searchbox.focus();
  732. }, 10);
  733. });
  734. this.$searchbox.on('click.dropdown.data-api focus.dropdown.data-api touchend.dropdown.data-api', function (e) {
  735. e.stopPropagation();
  736. });
  737. this.$searchbox.on('input propertychange', function () {
  738. if (that.$searchbox.val()) {
  739. if (that.options.searchAccentInsensitive) {
  740. that.$lis.not('.is-hidden').removeClass('hide').find('a').not(':aicontains(' + normalizeToBase(that.$searchbox.val()) + ')').parent().addClass('hide');
  741. } else {
  742. that.$lis.not('.is-hidden').removeClass('hide').find('a').not(':icontains(' + that.$searchbox.val() + ')').parent().addClass('hide');
  743. }
  744. if (!that.$menu.find('li').filter(':visible:not(.no-results)').length) {
  745. if (!!no_results.parent().length) no_results.remove();
  746. no_results.html(that.options.noneResultsText + ' "' + htmlEscape(that.$searchbox.val()) + '"').show();
  747. that.$menu.find('li').last().after(no_results);
  748. } else if (!!no_results.parent().length) {
  749. no_results.remove();
  750. }
  751. } else {
  752. that.$lis.not('.is-hidden').removeClass('hide');
  753. if (!!no_results.parent().length) no_results.remove();
  754. }
  755. that.$menu.find('li.active').removeClass('active');
  756. that.$menu.find('li').filter(':visible:not(.divider)').eq(0).addClass('active').find('a').focus();
  757. $(this).focus();
  758. });
  759. },
  760. val: function (value) {
  761. if (typeof value !== 'undefined') {
  762. this.$element.val(value);
  763. this.render();
  764. return this.$element;
  765. } else {
  766. return this.$element.val();
  767. }
  768. },
  769. selectAll: function () {
  770. this.findLis();
  771. this.$lis.not('.divider').not('.disabled').not('.selected').filter(':visible').find('a').click();
  772. },
  773. deselectAll: function () {
  774. this.findLis();
  775. this.$lis.not('.divider').not('.disabled').filter('.selected').filter(':visible').find('a').click();
  776. },
  777. keydown: function (e) {
  778. var $this = $(this),
  779. $parent = ($this.is('input')) ? $this.parent().parent() : $this.parent(),
  780. $items,
  781. that = $parent.data('this'),
  782. index,
  783. next,
  784. first,
  785. last,
  786. prev,
  787. nextPrev,
  788. prevIndex,
  789. isActive,
  790. keyCodeMap = {
  791. 32: ' ',
  792. 48: '0',
  793. 49: '1',
  794. 50: '2',
  795. 51: '3',
  796. 52: '4',
  797. 53: '5',
  798. 54: '6',
  799. 55: '7',
  800. 56: '8',
  801. 57: '9',
  802. 59: ';',
  803. 65: 'a',
  804. 66: 'b',
  805. 67: 'c',
  806. 68: 'd',
  807. 69: 'e',
  808. 70: 'f',
  809. 71: 'g',
  810. 72: 'h',
  811. 73: 'i',
  812. 74: 'j',
  813. 75: 'k',
  814. 76: 'l',
  815. 77: 'm',
  816. 78: 'n',
  817. 79: 'o',
  818. 80: 'p',
  819. 81: 'q',
  820. 82: 'r',
  821. 83: 's',
  822. 84: 't',
  823. 85: 'u',
  824. 86: 'v',
  825. 87: 'w',
  826. 88: 'x',
  827. 89: 'y',
  828. 90: 'z',
  829. 96: '0',
  830. 97: '1',
  831. 98: '2',
  832. 99: '3',
  833. 100: '4',
  834. 101: '5',
  835. 102: '6',
  836. 103: '7',
  837. 104: '8',
  838. 105: '9'
  839. };
  840. if (that.options.liveSearch) $parent = $this.parent().parent();
  841. if (that.options.container) $parent = that.$menu;
  842. $items = $('[role=menu] li a', $parent);
  843. isActive = that.$menu.parent().hasClass('open');
  844. if (!isActive && /([0-9]|[A-z])/.test(String.fromCharCode(e.keyCode))) {
  845. if (!that.options.container) {
  846. that.setSize();
  847. that.$menu.parent().addClass('open');
  848. isActive = true;
  849. } else {
  850. that.$newElement.trigger('click');
  851. }
  852. that.$searchbox.focus();
  853. }
  854. if (that.options.liveSearch) {
  855. if (/(^9$|27)/.test(e.keyCode.toString(10)) && isActive && that.$menu.find('.active').length === 0) {
  856. e.preventDefault();
  857. that.$menu.parent().removeClass('open');
  858. that.$button.focus();
  859. }
  860. $items = $('[role=menu] li:not(.divider):not(.dropdown-header):visible', $parent);
  861. if (!$this.val() && !/(38|40)/.test(e.keyCode.toString(10))) {
  862. if ($items.filter('.active').length === 0) {
  863. if (that.options.searchAccentInsensitive) {
  864. $items = that.$newElement.find('li').filter(':aicontains(' + normalizeToBase(keyCodeMap[e.keyCode]) + ')');
  865. } else {
  866. $items = that.$newElement.find('li').filter(':icontains(' + keyCodeMap[e.keyCode] + ')');
  867. }
  868. }
  869. }
  870. }
  871. if (!$items.length) return;
  872. if (/(38|40)/.test(e.keyCode.toString(10))) {
  873. index = $items.index($items.filter(':focus'));
  874. first = $items.parent(':not(.disabled):visible').first().index();
  875. last = $items.parent(':not(.disabled):visible').last().index();
  876. next = $items.eq(index).parent().nextAll(':not(.disabled):visible').eq(0).index();
  877. prev = $items.eq(index).parent().prevAll(':not(.disabled):visible').eq(0).index();
  878. nextPrev = $items.eq(next).parent().prevAll(':not(.disabled):visible').eq(0).index();
  879. if (that.options.liveSearch) {
  880. $items.each(function (i) {
  881. if ($(this).is(':not(.disabled)')) {
  882. $(this).data('index', i);
  883. }
  884. });
  885. index = $items.index($items.filter('.active'));
  886. first = $items.filter(':not(.disabled):visible').first().data('index');
  887. last = $items.filter(':not(.disabled):visible').last().data('index');
  888. next = $items.eq(index).nextAll(':not(.disabled):visible').eq(0).data('index');
  889. prev = $items.eq(index).prevAll(':not(.disabled):visible').eq(0).data('index');
  890. nextPrev = $items.eq(next).prevAll(':not(.disabled):visible').eq(0).data('index');
  891. }
  892. prevIndex = $this.data('prevIndex');
  893. if (e.keyCode == 38) {
  894. if (that.options.liveSearch) index -= 1;
  895. if (index != nextPrev && index > prev) index = prev;
  896. if (index < first) index = first;
  897. if (index == prevIndex) index = last;
  898. }
  899. if (e.keyCode == 40) {
  900. if (that.options.liveSearch) index += 1;
  901. if (index == -1) index = 0;
  902. if (index != nextPrev && index < next) index = next;
  903. if (index > last) index = last;
  904. if (index == prevIndex) index = first;
  905. }
  906. $this.data('prevIndex', index);
  907. if (!that.options.liveSearch) {
  908. $items.eq(index).focus();
  909. } else {
  910. e.preventDefault();
  911. if (!$this.is('.dropdown-toggle')) {
  912. $items.removeClass('active');
  913. $items.eq(index).addClass('active').find('a').focus();
  914. $this.focus();
  915. }
  916. }
  917. } else if (!$this.is('input')) {
  918. var keyIndex = [],
  919. count,
  920. prevKey;
  921. $items.each(function () {
  922. if ($(this).parent().is(':not(.disabled)')) {
  923. if ($.trim($(this).text().toLowerCase()).substring(0, 1) == keyCodeMap[e.keyCode]) {
  924. keyIndex.push($(this).parent().index());
  925. }
  926. }
  927. });
  928. count = $(document).data('keycount');
  929. count++;
  930. $(document).data('keycount', count);
  931. prevKey = $.trim($(':focus').text().toLowerCase()).substring(0, 1);
  932. if (prevKey != keyCodeMap[e.keyCode]) {
  933. count = 1;
  934. $(document).data('keycount', count);
  935. } else if (count >= keyIndex.length) {
  936. $(document).data('keycount', 0);
  937. if (count > keyIndex.length) count = 1;
  938. }
  939. $items.eq(keyIndex[count - 1]).focus();
  940. }
  941. // Select focused option if "Enter", "Spacebar" or "Tab" (when selectOnTab is true) are pressed inside the menu.
  942. if ((/(13|32)/.test(e.keyCode.toString(10)) || (/(^9$)/.test(e.keyCode.toString(10)) && that.options.selectOnTab)) && isActive) {
  943. if (!/(32)/.test(e.keyCode.toString(10))) e.preventDefault();
  944. if (!that.options.liveSearch) {
  945. $(':focus').click();
  946. } else if (!/(32)/.test(e.keyCode.toString(10))) {
  947. that.$menu.find('.active a').click();
  948. $this.focus();
  949. }
  950. $(document).data('keycount', 0);
  951. }
  952. if ((/(^9$|27)/.test(e.keyCode.toString(10)) && isActive && (that.multiple || that.options.liveSearch)) || (/(27)/.test(e.keyCode.toString(10)) && !isActive)) {
  953. that.$menu.parent().removeClass('open');
  954. that.$button.focus();
  955. }
  956. },
  957. mobile: function () {
  958. this.$element.addClass('mobile-device').appendTo(this.$newElement);
  959. if (this.options.container) this.$menu.hide();
  960. },
  961. refresh: function () {
  962. this.$lis = null;
  963. this.reloadLi();
  964. this.render();
  965. this.setWidth();
  966. this.setStyle();
  967. this.checkDisabled();
  968. this.liHeight();
  969. },
  970. update: function () {
  971. this.reloadLi();
  972. this.setWidth();
  973. this.setStyle();
  974. this.checkDisabled();
  975. this.liHeight();
  976. },
  977. hide: function () {
  978. this.$newElement.hide();
  979. },
  980. show: function () {
  981. this.$newElement.show();
  982. },
  983. remove: function () {
  984. this.$newElement.remove();
  985. this.$element.remove();
  986. }
  987. };
  988. // SELECTPICKER PLUGIN DEFINITION
  989. // ==============================
  990. function Plugin(option, event) {
  991. // get the args of the outer function..
  992. var args = arguments;
  993. // The arguments of the function are explicitly re-defined from the argument list, because the shift causes them
  994. // to get lost
  995. //noinspection JSDuplicatedDeclaration
  996. var _option = option,
  997. option = args[0],
  998. event = args[1];
  999. [].shift.apply(args);
  1000. // This fixes a bug in the js implementation on android 2.3 #715
  1001. if (typeof option == 'undefined') {
  1002. option = _option;
  1003. }
  1004. var value;
  1005. var chain = this.each(function () {
  1006. var $this = $(this);
  1007. if ($this.is('select')) {
  1008. var data = $this.data('selectpicker'),
  1009. options = typeof option == 'object' && option;
  1010. if (!data) {
  1011. var config = $.extend({}, Selectpicker.DEFAULTS, $.fn.selectpicker.defaults || {}, $this.data(), options);
  1012. $this.data('selectpicker', (data = new Selectpicker(this, config, event)));
  1013. } else if (options) {
  1014. for (var i in options) {
  1015. if (options.hasOwnProperty(i)) {
  1016. data.options[i] = options[i];
  1017. }
  1018. }
  1019. }
  1020. if (typeof option == 'string') {
  1021. if (data[option] instanceof Function) {
  1022. value = data[option].apply(data, args);
  1023. } else {
  1024. value = data.options[option];
  1025. }
  1026. }
  1027. }
  1028. });
  1029. if (typeof value !== 'undefined') {
  1030. //noinspection JSUnusedAssignment
  1031. return value;
  1032. } else {
  1033. return chain;
  1034. }
  1035. }
  1036. var old = $.fn.selectpicker;
  1037. $.fn.selectpicker = Plugin;
  1038. $.fn.selectpicker.Constructor = Selectpicker;
  1039. // SELECTPICKER NO CONFLICT
  1040. // ========================
  1041. $.fn.selectpicker.noConflict = function () {
  1042. $.fn.selectpicker = old;
  1043. return this;
  1044. };
  1045. $(document)
  1046. .data('keycount', 0)
  1047. .on('keydown', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role=menu], .bs-searchbox input', Selectpicker.prototype.keydown)
  1048. .on('focusin.modal', '.bootstrap-select [data-toggle=dropdown], .bootstrap-select [role=menu], .bs-searchbox input', function (e) {
  1049. e.stopPropagation();
  1050. });
  1051. // SELECTPICKER DATA-API
  1052. // =====================
  1053. $(window).on('load.bs.select.data-api', function () {
  1054. $('.selectpicker').each(function () {
  1055. var $selectpicker = $(this);
  1056. Plugin.call($selectpicker, $selectpicker.data());
  1057. })
  1058. });
  1059. })(jQuery);