bootstrap-select.js 58 KB

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