bootstrap-select.js 58 KB

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