bootstrap-select.js 61 KB

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