bootstrap-select.js 60 KB

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