bootstrap-select.js 51 KB

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