bootstrap-select.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  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);