bootstrap-select.js 61 KB

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