bootstrap-select.js 53 KB

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