bootstrap-select.js 60 KB

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