bootstrap-multiselect.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  1. /**
  2. * Bootstrap Multiselect v0.9.8 (https://github.com/davidstutz/bootstrap-multiselect)
  3. *
  4. * Copyright 2012 - 2014 David Stutz
  5. *
  6. * Dual licensed under the BSD-3-Clause and the Apache License, Version 2.0.
  7. */
  8. !function($) {
  9. "use strict";// jshint ;_;
  10. if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) {
  11. ko.bindingHandlers.multiselect = {
  12. init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  13. var listOfSelectedItems = allBindingsAccessor().selectedOptions;
  14. var config = ko.utils.unwrapObservable(valueAccessor());
  15. $(element).multiselect(config);
  16. if (isObservableArray(listOfSelectedItems)) {
  17. // Set the initial selection state on the multiselect list.
  18. $(element).multiselect('select', ko.utils.unwrapObservable(listOfSelectedItems));
  19. // Subscribe to the selectedOptions: ko.observableArray
  20. listOfSelectedItems.subscribe(function (changes) {
  21. var addedArray = [], deletedArray = [];
  22. forEach(changes, function (change) {
  23. switch (change.status) {
  24. case 'added':
  25. addedArray.push(change.value);
  26. break;
  27. case 'deleted':
  28. deletedArray.push(change.value);
  29. break;
  30. }
  31. });
  32. if (addedArray.length > 0) {
  33. $(element).multiselect('select', addedArray);
  34. }
  35. if (deletedArray.length > 0) {
  36. $(element).multiselect('deselect', deletedArray);
  37. }
  38. }, null, "arrayChange");
  39. }
  40. },
  41. update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  42. var listOfItems = allBindingsAccessor().options,
  43. ms = $(element).data('multiselect'),
  44. config = ko.utils.unwrapObservable(valueAccessor());
  45. if (isObservableArray(listOfItems)) {
  46. // Subscribe to the options: ko.observableArray incase it changes later
  47. listOfItems.subscribe(function (theArray) {
  48. $(element).multiselect('rebuild');
  49. });
  50. }
  51. if (!ms) {
  52. $(element).multiselect(config);
  53. }
  54. else {
  55. ms.updateOriginalOptions();
  56. }
  57. }
  58. };
  59. }
  60. function isObservableArray(obj) {
  61. return ko.isObservable(obj) && !(obj.destroyAll === undefined);
  62. }
  63. function forEach(array, callback) {
  64. for (var index = 0; index < array.length; ++index) {
  65. callback(array[index]);
  66. }
  67. }
  68. /**
  69. * Constructor to create a new multiselect using the given select.
  70. *
  71. * @param {jQuery} select
  72. * @param {Object} options
  73. * @returns {Multiselect}
  74. */
  75. function Multiselect(select, options) {
  76. this.$select = $(select);
  77. this.options = this.mergeOptions($.extend({}, options, this.$select.data()));
  78. // Initialization.
  79. // We have to clone to create a new reference.
  80. this.originalOptions = this.$select.clone()[0].options;
  81. this.query = '';
  82. this.searchTimeout = null;
  83. this.options.multiple = this.$select.attr('multiple') === "multiple";
  84. this.options.onChange = $.proxy(this.options.onChange, this);
  85. this.options.onDropdownShow = $.proxy(this.options.onDropdownShow, this);
  86. this.options.onDropdownHide = $.proxy(this.options.onDropdownHide, this);
  87. this.options.onDropdownShown = $.proxy(this.options.onDropdownShown, this);
  88. this.options.onDropdownHidden = $.proxy(this.options.onDropdownHidden, this);
  89. // Build select all if enabled.
  90. this.buildContainer();
  91. this.buildButton();
  92. this.buildDropdown();
  93. this.buildSelectAll();
  94. this.buildDropdownOptions();
  95. this.buildFilter();
  96. this.updateButtonText();
  97. this.updateSelectAll();
  98. if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) {
  99. this.disable();
  100. }
  101. this.$select.hide().after(this.$container);
  102. };
  103. Multiselect.prototype = {
  104. defaults: {
  105. /**
  106. * Default text function will either print 'None selected' in case no
  107. * option is selected or a list of the selected options up to a length
  108. * of 3 selected options.
  109. *
  110. * @param {jQuery} options
  111. * @param {jQuery} select
  112. * @returns {String}
  113. */
  114. buttonText: function(options, select) {
  115. if (options.length === 0) {
  116. return this.nonSelectedText + ' <b class="fa fa-caret-down"></b>';//ACE
  117. }
  118. else if (options.length == $('option', $(select)).length) {
  119. return this.allSelectedText + ' <b class="fa fa-caret-down"></b>';//ACE
  120. }
  121. else if (options.length > this.numberDisplayed) {
  122. return options.length + ' ' + this.nSelectedText + ' <b class="fa fa-caret-down"></b>';//ACE
  123. }
  124. else {
  125. var selected = '';
  126. options.each(function() {
  127. var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html();
  128. selected += label + ', ';
  129. });
  130. return selected.substr(0, selected.length - 2) + ' <b class="fa fa-caret-down"></b>';//ACE
  131. }
  132. },
  133. /**
  134. * Updates the title of the button similar to the buttonText function.
  135. *
  136. * @param {jQuery} options
  137. * @param {jQuery} select
  138. * @returns {@exp;selected@call;substr}
  139. */
  140. buttonTitle: function(options, select) {
  141. if (options.length === 0) {
  142. return this.nonSelectedText;
  143. }
  144. else {
  145. var selected = '';
  146. options.each(function () {
  147. selected += $(this).text() + ', ';
  148. });
  149. return selected.substr(0, selected.length - 2);
  150. }
  151. },
  152. /**
  153. * Create a label.
  154. *
  155. * @param {jQuery} element
  156. * @returns {String}
  157. */
  158. label: function(element){
  159. return $(element).attr('label') || $(element).html();
  160. },
  161. /**
  162. * Triggered on change of the multiselect.
  163. *
  164. * Not triggered when selecting/deselecting options manually.
  165. *
  166. * @param {jQuery} option
  167. * @param {Boolean} checked
  168. */
  169. onChange : function(option, checked) {
  170. },
  171. /**
  172. * Triggered when the dropdown is shown.
  173. *
  174. * @param {jQuery} event
  175. */
  176. onDropdownShow: function(event) {
  177. },
  178. /**
  179. * Triggered when the dropdown is hidden.
  180. *
  181. * @param {jQuery} event
  182. */
  183. onDropdownHide: function(event) {
  184. },
  185. /**
  186. * Triggered after the dropdown is shown.
  187. *
  188. * @param {jQuery} event
  189. */
  190. onDropdownShown: function(event) {
  191. },
  192. /**
  193. * Triggered after the dropdown is hidden.
  194. *
  195. * @param {jQuery} event
  196. */
  197. onDropdownHidden: function(event) {
  198. },
  199. buttonClass: 'btn btn-default',
  200. buttonWidth: 'auto',
  201. buttonContainer: '<div class="btn-group" />',
  202. dropRight: false,
  203. selectedClass: 'active',
  204. // Maximum height of the dropdown menu.
  205. // If maximum height is exceeded a scrollbar will be displayed.
  206. maxHeight: false,
  207. checkboxName: false,
  208. includeSelectAllOption: false,
  209. includeSelectAllIfMoreThan: 0,
  210. selectAllText: ' Select all',
  211. selectAllValue: 'multiselect-all',
  212. selectAllName: false,
  213. enableFiltering: false,
  214. enableCaseInsensitiveFiltering: false,
  215. enableClickableOptGroups: false,
  216. filterPlaceholder: 'Search',
  217. // possible options: 'text', 'value', 'both'
  218. filterBehavior: 'text',
  219. includeFilterClearBtn: true,
  220. preventInputChangeEvent: false,
  221. nonSelectedText: 'None selected',
  222. nSelectedText: 'selected',
  223. allSelectedText: 'All selected',
  224. numberDisplayed: 3,
  225. disableIfEmpty: false,
  226. templates: {
  227. button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>',
  228. ul: '<ul class="multiselect-container dropdown-menu"></ul>',
  229. filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
  230. filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default multiselect-clear-filter" type="button"><i class="glyphicon glyphicon-remove-circle"></i></button></span>',
  231. li: '<li><a href="javascript:void(0);"><label></label></a></li>',
  232. divider: '<li class="multiselect-item divider"></li>',
  233. liGroup: '<li class="multiselect-item multiselect-group"><label></label></li>'
  234. }
  235. },
  236. constructor: Multiselect,
  237. /**
  238. * Builds the container of the multiselect.
  239. */
  240. buildContainer: function() {
  241. this.$container = $(this.options.buttonContainer);
  242. this.$container.on('show.bs.dropdown', this.options.onDropdownShow);
  243. this.$container.on('hide.bs.dropdown', this.options.onDropdownHide);
  244. this.$container.on('shown.bs.dropdown', this.options.onDropdownShown);
  245. this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden);
  246. },
  247. /**
  248. * Builds the button of the multiselect.
  249. */
  250. buildButton: function() {
  251. this.$button = $(this.options.templates.button).addClass(this.options.buttonClass);
  252. // Adopt active state.
  253. if (this.$select.prop('disabled')) {
  254. this.disable();
  255. }
  256. else {
  257. this.enable();
  258. }
  259. // Manually add button width if set.
  260. if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') {
  261. this.$button.css({
  262. 'width' : this.options.buttonWidth
  263. });
  264. this.$container.css({
  265. 'width': this.options.buttonWidth
  266. });
  267. }
  268. // Keep the tab index from the select.
  269. var tabindex = this.$select.attr('tabindex');
  270. if (tabindex) {
  271. this.$button.attr('tabindex', tabindex);
  272. }
  273. this.$container.prepend(this.$button);
  274. },
  275. /**
  276. * Builds the ul representing the dropdown menu.
  277. */
  278. buildDropdown: function() {
  279. // Build ul.
  280. this.$ul = $(this.options.templates.ul);
  281. if (this.options.dropRight) {
  282. this.$ul.addClass('pull-right');
  283. }
  284. // Set max height of dropdown menu to activate auto scrollbar.
  285. if (this.options.maxHeight) {
  286. // TODO: Add a class for this option to move the css declarations.
  287. this.$ul.css({
  288. 'max-height': this.options.maxHeight + 'px',
  289. 'overflow-y': 'auto',
  290. 'overflow-x': 'hidden'
  291. });
  292. }
  293. this.$container.append(this.$ul);
  294. },
  295. /**
  296. * Build the dropdown options and binds all nessecary events.
  297. *
  298. * Uses createDivider and createOptionValue to create the necessary options.
  299. */
  300. buildDropdownOptions: function() {
  301. this.$select.children().each($.proxy(function(index, element) {
  302. var $element = $(element);
  303. // Support optgroups and options without a group simultaneously.
  304. var tag = $element.prop('tagName')
  305. .toLowerCase();
  306. if ($element.prop('value') === this.options.selectAllValue) {
  307. return;
  308. }
  309. if (tag === 'optgroup') {
  310. this.createOptgroup(element);
  311. }
  312. else if (tag === 'option') {
  313. if ($element.data('role') === 'divider') {
  314. this.createDivider();
  315. }
  316. else {
  317. this.createOptionValue(element);
  318. }
  319. }
  320. // Other illegal tags will be ignored.
  321. }, this));
  322. // Bind the change event on the dropdown elements.
  323. $('li input', this.$ul).on('change', $.proxy(function(event) {
  324. var $target = $(event.target);
  325. var checked = $target.prop('checked') || false;
  326. var isSelectAllOption = $target.val() === this.options.selectAllValue;
  327. // Apply or unapply the configured selected class.
  328. if (this.options.selectedClass) {
  329. if (checked) {
  330. $target.closest('li')
  331. .addClass(this.options.selectedClass);
  332. }
  333. else {
  334. $target.closest('li')
  335. .removeClass(this.options.selectedClass);
  336. }
  337. }
  338. // Get the corresponding option.
  339. var value = $target.val();
  340. var $option = this.getOptionByValue(value);
  341. var $optionsNotThis = $('option', this.$select).not($option);
  342. var $checkboxesNotThis = $('input', this.$container).not($target);
  343. if (isSelectAllOption) {
  344. if (checked) {
  345. this.selectAll();
  346. }
  347. else {
  348. this.deselectAll();
  349. }
  350. }
  351. if(!isSelectAllOption){
  352. if (checked) {
  353. $option.prop('selected', true);
  354. if (this.options.multiple) {
  355. // Simply select additional option.
  356. $option.prop('selected', true);
  357. }
  358. else {
  359. // Unselect all other options and corresponding checkboxes.
  360. if (this.options.selectedClass) {
  361. $($checkboxesNotThis).closest('li').removeClass(this.options.selectedClass);
  362. }
  363. $($checkboxesNotThis).prop('checked', false);
  364. $optionsNotThis.prop('selected', false);
  365. // It's a single selection, so close.
  366. this.$button.click();
  367. }
  368. if (this.options.selectedClass === "active") {
  369. $optionsNotThis.closest("a").css("outline", "");
  370. }
  371. }
  372. else {
  373. // Unselect option.
  374. $option.prop('selected', false);
  375. }
  376. }
  377. this.$select.change();
  378. this.updateButtonText();
  379. this.updateSelectAll();
  380. this.options.onChange($option, checked);
  381. if(this.options.preventInputChangeEvent) {
  382. return false;
  383. }
  384. }, this));
  385. $('li a', this.$ul).on('touchstart click', function(event) {
  386. event.stopPropagation();
  387. var $target = $(event.target);
  388. try {//ACE -- for IE8
  389. if (document.getSelection().type === 'Range') {
  390. var $input = $(this).find("input:first");
  391. $input.prop("checked", !$input.prop("checked"))
  392. .trigger("change");
  393. }
  394. } catch(e) {}
  395. if (event.shiftKey) {
  396. var checked = $target.prop('checked') || false;
  397. if (checked) {
  398. var prev = $target.closest('li')
  399. .siblings('li[class="active"]:first');
  400. var currentIdx = $target.closest('li')
  401. .index();
  402. var prevIdx = prev.index();
  403. if (currentIdx > prevIdx) {
  404. $target.closest("li").prevUntil(prev).each(
  405. function() {
  406. $(this).find("input:first").prop("checked", true)
  407. .trigger("change");
  408. }
  409. );
  410. }
  411. else {
  412. $target.closest("li").nextUntil(prev).each(
  413. function() {
  414. $(this).find("input:first").prop("checked", true)
  415. .trigger("change");
  416. }
  417. );
  418. }
  419. }
  420. }
  421. $target.blur();
  422. });
  423. // Keyboard support.
  424. this.$container.off('keydown.multiselect').on('keydown.multiselect', $.proxy(function(event) {
  425. if ($('input[type="text"]', this.$container).is(':focus')) {
  426. return;
  427. }
  428. if (event.keyCode === 9 && this.$container.hasClass('open')) {
  429. this.$button.click();
  430. }
  431. else {
  432. var $items = $(this.$container).find("li:not(.divider):not(.disabled) a").filter(":visible");
  433. if (!$items.length) {
  434. return;
  435. }
  436. var index = $items.index($items.filter(':focus'));
  437. // Navigation up.
  438. if (event.keyCode === 38 && index > 0) {
  439. index--;
  440. }
  441. // Navigate down.
  442. else if (event.keyCode === 40 && index < $items.length - 1) {
  443. index++;
  444. }
  445. else if (!~index) {
  446. index = 0;
  447. }
  448. var $current = $items.eq(index);
  449. $current.focus();
  450. if (event.keyCode === 32 || event.keyCode === 13) {
  451. var $checkbox = $current.find('input');
  452. $checkbox.prop("checked", !$checkbox.prop("checked"));
  453. $checkbox.change();
  454. }
  455. event.stopPropagation();
  456. event.preventDefault();
  457. }
  458. }, this));
  459. if(this.options.enableClickableOptGroups && this.options.multiple) {
  460. $('li.multiselect-group', this.$ul).on('click', $.proxy(function(event) {
  461. event.stopPropagation();
  462. var group = $(event.target).parent();
  463. // Search all option in optgroup
  464. var $options = group.nextUntil('li.multiselect-group');
  465. // check or uncheck items
  466. var allChecked = true;
  467. var optionInputs = $options.find('input');
  468. optionInputs.each(function() {
  469. allChecked = allChecked && $(this).prop('checked');
  470. });
  471. optionInputs.prop('checked', !allChecked).trigger('change');
  472. }, this));
  473. }
  474. },
  475. /**
  476. * Create an option using the given select option.
  477. *
  478. * @param {jQuery} element
  479. */
  480. createOptionValue: function(element) {
  481. var $element = $(element);
  482. if ($element.is(':selected')) {
  483. $element.prop('selected', true);
  484. }
  485. // Support the label attribute on options.
  486. var label = this.options.label(element);
  487. var value = $element.val();
  488. var inputType = this.options.multiple ? "checkbox" : "radio";
  489. var $li = $(this.options.templates.li);
  490. var $label = $('label', $li);
  491. $label.addClass(inputType);
  492. var $checkbox = $('<input/>').attr('type', inputType).addClass('ace');//ACE
  493. if (this.options.checkboxName) {
  494. $checkbox.attr('name', this.options.checkboxName);
  495. }
  496. $label.append($checkbox);
  497. $checkbox.after('<span class="lbl" />');//ACE
  498. var selected = $element.prop('selected') || false;
  499. $checkbox.val(value);
  500. if (value === this.options.selectAllValue) {
  501. $li.addClass("multiselect-item multiselect-all");
  502. $checkbox.parent().parent()
  503. .addClass('multiselect-all');
  504. }
  505. $label.append(" " + label);
  506. $label.attr('title', $element.attr('title'));
  507. this.$ul.append($li);
  508. if ($element.is(':disabled')) {
  509. $checkbox.attr('disabled', 'disabled')
  510. .prop('disabled', true)
  511. .closest('a')
  512. .attr("tabindex", "-1")
  513. .closest('li')
  514. .addClass('disabled');
  515. }
  516. $checkbox.prop('checked', selected);
  517. if (selected && this.options.selectedClass) {
  518. $checkbox.closest('li')
  519. .addClass(this.options.selectedClass);
  520. }
  521. },
  522. /**
  523. * Creates a divider using the given select option.
  524. *
  525. * @param {jQuery} element
  526. */
  527. createDivider: function(element) {
  528. var $divider = $(this.options.templates.divider);
  529. this.$ul.append($divider);
  530. },
  531. /**
  532. * Creates an optgroup.
  533. *
  534. * @param {jQuery} group
  535. */
  536. createOptgroup: function(group) {
  537. var groupName = $(group).prop('label');
  538. // Add a header for the group.
  539. var $li = $(this.options.templates.liGroup);
  540. $('label', $li).text(groupName);
  541. if (this.options.enableClickableOptGroups) {
  542. $li.addClass('multiselect-group-clickable');
  543. }
  544. this.$ul.append($li);
  545. if ($(group).is(':disabled')) {
  546. $li.addClass('disabled');
  547. }
  548. // Add the options of the group.
  549. $('option', group).each($.proxy(function(index, element) {
  550. this.createOptionValue(element);
  551. }, this));
  552. },
  553. /**
  554. * Build the selct all.
  555. *
  556. * Checks if a select all has already been created.
  557. */
  558. buildSelectAll: function() {
  559. if (typeof this.options.selectAllValue === 'number') {
  560. this.options.selectAllValue = this.options.selectAllValue.toString();
  561. }
  562. var alreadyHasSelectAll = this.hasSelectAll();
  563. if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple
  564. && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) {
  565. // Check whether to add a divider after the select all.
  566. if (this.options.includeSelectAllDivider) {
  567. this.$ul.prepend($(this.options.templates.divider));
  568. }
  569. var $li = $(this.options.templates.li);
  570. $('label', $li).addClass("checkbox");
  571. if (this.options.selectAllName) {
  572. $('label', $li).append('<input type="checkbox" name="' + this.options.selectAllName + '" />');
  573. }
  574. else {
  575. $('label', $li).append('<input type="checkbox" />');
  576. }
  577. var $checkbox = $('input', $li);
  578. $checkbox.val(this.options.selectAllValue);
  579. $li.addClass("multiselect-item multiselect-all");
  580. $checkbox.parent().parent()
  581. .addClass('multiselect-all');
  582. $('label', $li).append(" " + this.options.selectAllText);
  583. this.$ul.prepend($li);
  584. $checkbox.prop('checked', false);
  585. }
  586. },
  587. /**
  588. * Builds the filter.
  589. */
  590. buildFilter: function() {
  591. // Build filter if filtering OR case insensitive filtering is enabled and the number of options exceeds (or equals) enableFilterLength.
  592. if (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering) {
  593. var enableFilterLength = Math.max(this.options.enableFiltering, this.options.enableCaseInsensitiveFiltering);
  594. if (this.$select.find('option').length >= enableFilterLength) {
  595. this.$filter = $(this.options.templates.filter);
  596. $('input', this.$filter).attr('placeholder', this.options.filterPlaceholder);
  597. // Adds optional filter clear button
  598. if(this.options.includeFilterClearBtn){
  599. var clearBtn = $(this.options.templates.filterClearBtn);
  600. clearBtn.on('click', $.proxy(function(event){
  601. clearTimeout(this.searchTimeout);
  602. this.$filter.find('.multiselect-search').val('');
  603. $('li', this.$ul).show().removeClass("filter-hidden");
  604. this.updateSelectAll();
  605. }, this));
  606. this.$filter.find('.input-group').append(clearBtn);
  607. }
  608. this.$ul.prepend(this.$filter);
  609. this.$filter.val(this.query).on('click', function(event) {
  610. event.stopPropagation();
  611. }).on('input keydown', $.proxy(function(event) {
  612. // Cancel enter key default behaviour
  613. if (event.which === 13) {
  614. event.preventDefault();
  615. }
  616. // This is useful to catch "keydown" events after the browser has updated the control.
  617. clearTimeout(this.searchTimeout);
  618. this.searchTimeout = this.asyncFunction($.proxy(function() {
  619. if (this.query !== event.target.value) {
  620. this.query = event.target.value;
  621. var currentGroup, currentGroupVisible;
  622. $.each($('li', this.$ul), $.proxy(function(index, element) {
  623. var value = $('input', element).val();
  624. var text = $('label', element).text();
  625. var filterCandidate = '';
  626. if ((this.options.filterBehavior === 'text')) {
  627. filterCandidate = text;
  628. }
  629. else if ((this.options.filterBehavior === 'value')) {
  630. filterCandidate = value;
  631. }
  632. else if (this.options.filterBehavior === 'both') {
  633. filterCandidate = text + '\n' + value;
  634. }
  635. if (value !== this.options.selectAllValue && text) {
  636. // By default lets assume that element is not
  637. // interesting for this search.
  638. var showElement = false;
  639. if (this.options.enableCaseInsensitiveFiltering && filterCandidate.toLowerCase().indexOf(this.query.toLowerCase()) > -1) {
  640. showElement = true;
  641. }
  642. else if (filterCandidate.indexOf(this.query) > -1) {
  643. showElement = true;
  644. }
  645. // Toggle current element (group or group item) according to showElement boolean.
  646. $(element).toggle(showElement).toggleClass('filter-hidden', !showElement);
  647. // Differentiate groups and group items.
  648. if ($(element).hasClass('multiselect-group')) {
  649. // Remember group status.
  650. currentGroup = element;
  651. currentGroupVisible = showElement;
  652. }
  653. else {
  654. // Show group name when at least one of its items is visible.
  655. if (showElement) {
  656. $(currentGroup).show().removeClass('filter-hidden');
  657. }
  658. // Show all group items when group name satisfies filter.
  659. if (!showElement && currentGroupVisible) {
  660. $(element).show().removeClass('filter-hidden');
  661. }
  662. }
  663. }
  664. }, this));
  665. }
  666. this.updateSelectAll();
  667. }, this), 300, this);
  668. }, this));
  669. }
  670. }
  671. },
  672. /**
  673. * Unbinds the whole plugin.
  674. */
  675. destroy: function() {
  676. this.$container.remove();
  677. this.$select.show();
  678. this.$select.data('multiselect', null);
  679. },
  680. /**
  681. * Refreshs the multiselect based on the selected options of the select.
  682. */
  683. refresh: function() {
  684. $('option', this.$select).each($.proxy(function(index, element) {
  685. var $input = $('li input', this.$ul).filter(function() {
  686. return $(this).val() === $(element).val();
  687. });
  688. if ($(element).is(':selected')) {
  689. $input.prop('checked', true);
  690. if (this.options.selectedClass) {
  691. $input.closest('li')
  692. .addClass(this.options.selectedClass);
  693. }
  694. }
  695. else {
  696. $input.prop('checked', false);
  697. if (this.options.selectedClass) {
  698. $input.closest('li')
  699. .removeClass(this.options.selectedClass);
  700. }
  701. }
  702. if ($(element).is(":disabled")) {
  703. $input.attr('disabled', 'disabled')
  704. .prop('disabled', true)
  705. .closest('li')
  706. .addClass('disabled');
  707. }
  708. else {
  709. $input.prop('disabled', false)
  710. .closest('li')
  711. .removeClass('disabled');
  712. }
  713. }, this));
  714. this.updateButtonText();
  715. this.updateSelectAll();
  716. },
  717. /**
  718. * Select all options of the given values.
  719. *
  720. * If triggerOnChange is set to true, the on change event is triggered if
  721. * and only if one value is passed.
  722. *
  723. * @param {Array} selectValues
  724. * @param {Boolean} triggerOnChange
  725. */
  726. select: function(selectValues, triggerOnChange) {
  727. if(!$.isArray(selectValues)) {
  728. selectValues = [selectValues];
  729. }
  730. for (var i = 0; i < selectValues.length; i++) {
  731. var value = selectValues[i];
  732. if (value === null || value === undefined) {
  733. continue;
  734. }
  735. var $option = this.getOptionByValue(value);
  736. var $checkbox = this.getInputByValue(value);
  737. if($option === undefined || $checkbox === undefined) {
  738. continue;
  739. }
  740. if (!this.options.multiple) {
  741. this.deselectAll(false);
  742. }
  743. if (this.options.selectedClass) {
  744. $checkbox.closest('li')
  745. .addClass(this.options.selectedClass);
  746. }
  747. $checkbox.prop('checked', true);
  748. $option.prop('selected', true);
  749. }
  750. this.updateButtonText();
  751. this.updateSelectAll();
  752. if (triggerOnChange && selectValues.length === 1) {
  753. this.options.onChange($option, true);
  754. }
  755. },
  756. /**
  757. * Clears all selected items.
  758. */
  759. clearSelection: function () {
  760. this.deselectAll(false);
  761. this.updateButtonText();
  762. this.updateSelectAll();
  763. },
  764. /**
  765. * Deselects all options of the given values.
  766. *
  767. * If triggerOnChange is set to true, the on change event is triggered, if
  768. * and only if one value is passed.
  769. *
  770. * @param {Array} deselectValues
  771. * @param {Boolean} triggerOnChange
  772. */
  773. deselect: function(deselectValues, triggerOnChange) {
  774. if(!$.isArray(deselectValues)) {
  775. deselectValues = [deselectValues];
  776. }
  777. for (var i = 0; i < deselectValues.length; i++) {
  778. var value = deselectValues[i];
  779. if (value === null || value === undefined) {
  780. continue;
  781. }
  782. var $option = this.getOptionByValue(value);
  783. var $checkbox = this.getInputByValue(value);
  784. if($option === undefined || $checkbox === undefined) {
  785. continue;
  786. }
  787. if (this.options.selectedClass) {
  788. $checkbox.closest('li')
  789. .removeClass(this.options.selectedClass);
  790. }
  791. $checkbox.prop('checked', false);
  792. $option.prop('selected', false);
  793. }
  794. this.updateButtonText();
  795. this.updateSelectAll();
  796. if (triggerOnChange && deselectValues.length === 1) {
  797. this.options.onChange($option, false);
  798. }
  799. },
  800. /**
  801. * Selects all enabled & visible options.
  802. *
  803. * If justVisible is true or not specified, only visible options are selected.
  804. *
  805. * @param {Boolean} justVisible
  806. */
  807. selectAll: function (justVisible) {
  808. var justVisible = typeof justVisible === 'undefined' ? true : justVisible;
  809. var allCheckboxes = $("li input[type='checkbox']:enabled", this.$ul);
  810. var visibleCheckboxes = allCheckboxes.filter(":visible");
  811. var allCheckboxesCount = allCheckboxes.length;
  812. var visibleCheckboxesCount = visibleCheckboxes.length;
  813. if(justVisible) {
  814. visibleCheckboxes.prop('checked', true);
  815. $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").addClass(this.options.selectedClass);
  816. }
  817. else {
  818. allCheckboxes.prop('checked', true);
  819. $("li:not(.divider):not(.disabled)", this.$ul).addClass(this.options.selectedClass);
  820. }
  821. if (allCheckboxesCount === visibleCheckboxesCount || justVisible === false) {
  822. $("option:enabled", this.$select).prop('selected', true);
  823. }
  824. else {
  825. var values = visibleCheckboxes.map(function() {
  826. return $(this).val();
  827. }).get();
  828. $("option:enabled", this.$select).filter(function(index) {
  829. return $.inArray($(this).val(), values) !== -1;
  830. }).prop('selected', true);
  831. }
  832. },
  833. /**
  834. * Deselects all options.
  835. *
  836. * If justVisible is true or not specified, only visible options are deselected.
  837. *
  838. * @param {Boolean} justVisible
  839. */
  840. deselectAll: function (justVisible) {
  841. var justVisible = typeof justVisible === 'undefined' ? true : justVisible;
  842. if(justVisible) {
  843. var visibleCheckboxes = $("li input[type='checkbox']:enabled", this.$ul).filter(":visible");
  844. visibleCheckboxes.prop('checked', false);
  845. var values = visibleCheckboxes.map(function() {
  846. return $(this).val();
  847. }).get();
  848. $("option:enabled", this.$select).filter(function(index) {
  849. return $.inArray($(this).val(), values) !== -1;
  850. }).prop('selected', false);
  851. if (this.options.selectedClass) {
  852. $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").removeClass(this.options.selectedClass);
  853. }
  854. }
  855. else {
  856. $("li input[type='checkbox']:enabled", this.$ul).prop('checked', false);
  857. $("option:enabled", this.$select).prop('selected', false);
  858. if (this.options.selectedClass) {
  859. $("li:not(.divider):not(.disabled)", this.$ul).removeClass(this.options.selectedClass);
  860. }
  861. }
  862. },
  863. /**
  864. * Rebuild the plugin.
  865. *
  866. * Rebuilds the dropdown, the filter and the select all option.
  867. */
  868. rebuild: function() {
  869. this.$ul.html('');
  870. // Important to distinguish between radios and checkboxes.
  871. this.options.multiple = this.$select.attr('multiple') === "multiple";
  872. this.buildSelectAll();
  873. this.buildDropdownOptions();
  874. this.buildFilter();
  875. this.updateButtonText();
  876. this.updateSelectAll();
  877. if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) {
  878. this.disable();
  879. }
  880. if (this.options.dropRight) {
  881. this.$ul.addClass('pull-right');
  882. }
  883. },
  884. /**
  885. * The provided data will be used to build the dropdown.
  886. */
  887. dataprovider: function(dataprovider) {
  888. var optionDOM = "";
  889. var groupCounter = 0;
  890. var tags = $(''); // create empty jQuery array
  891. $.each(dataprovider, function (index, option) {
  892. var tag;
  893. if ($.isArray(option.children)) { // create optiongroup tag
  894. groupCounter++;
  895. tag = $('<optgroup/>').attr({
  896. label: option.label || 'Group ' + groupCounter
  897. });
  898. forEach(option.children, function(subOption) { // add children option tags
  899. tag.append($('<option/>').attr({
  900. value: subOption.value,
  901. label: subOption.label || subOption.value,
  902. title: subOption.title,
  903. selected: !!subOption.selected
  904. }));
  905. });
  906. optionDOM += '</optgroup>';
  907. }
  908. else { // create option tag
  909. tag = $('<option/>').attr({
  910. value: option.value,
  911. label: option.label || option.value,
  912. title: option.title,
  913. selected: !!option.selected
  914. });
  915. }
  916. tags = tags.add(tag);
  917. });
  918. this.$select.empty().append(tags);
  919. this.rebuild();
  920. },
  921. /**
  922. * Enable the multiselect.
  923. */
  924. enable: function() {
  925. this.$select.prop('disabled', false);
  926. this.$button.prop('disabled', false)
  927. .removeClass('disabled');
  928. },
  929. /**
  930. * Disable the multiselect.
  931. */
  932. disable: function() {
  933. this.$select.prop('disabled', true);
  934. this.$button.prop('disabled', true)
  935. .addClass('disabled');
  936. },
  937. /**
  938. * Set the options.
  939. *
  940. * @param {Array} options
  941. */
  942. setOptions: function(options) {
  943. this.options = this.mergeOptions(options);
  944. },
  945. /**
  946. * Merges the given options with the default options.
  947. *
  948. * @param {Array} options
  949. * @returns {Array}
  950. */
  951. mergeOptions: function(options) {
  952. return $.extend(true, {}, this.defaults, options);
  953. },
  954. /**
  955. * Checks whether a select all checkbox is present.
  956. *
  957. * @returns {Boolean}
  958. */
  959. hasSelectAll: function() {
  960. return $('li.' + this.options.selectAllValue, this.$ul).length > 0;
  961. },
  962. /**
  963. * Updates the select all checkbox based on the currently displayed and selected checkboxes.
  964. */
  965. updateSelectAll: function() {
  966. if (this.hasSelectAll()) {
  967. var allBoxes = $("li:not(.multiselect-item):not(.filter-hidden) input:enabled", this.$ul);
  968. var allBoxesLength = allBoxes.length;
  969. var checkedBoxesLength = allBoxes.filter(":checked").length;
  970. var selectAllLi = $("li." + this.options.selectAllValue, this.$ul);
  971. var selectAllInput = selectAllLi.find("input");
  972. if (checkedBoxesLength > 0 && checkedBoxesLength === allBoxesLength) {
  973. selectAllInput.prop("checked", true);
  974. selectAllLi.addClass(this.options.selectedClass);
  975. }
  976. else {
  977. selectAllInput.prop("checked", false);
  978. selectAllLi.removeClass(this.options.selectedClass);
  979. }
  980. }
  981. },
  982. /**
  983. * Update the button text and its title based on the currently selected options.
  984. */
  985. updateButtonText: function() {
  986. var options = this.getSelected();
  987. // First update the displayed button text.
  988. $('.multiselect', this.$container).html(this.options.buttonText(options, this.$select));
  989. // Now update the title attribute of the button.
  990. $('.multiselect', this.$container).attr('title', this.options.buttonTitle(options, this.$select));
  991. },
  992. /**
  993. * Get all selected options.
  994. *
  995. * @returns {jQUery}
  996. */
  997. getSelected: function() {
  998. return $('option', this.$select).filter(":selected");
  999. },
  1000. /**
  1001. * Gets a select option by its value.
  1002. *
  1003. * @param {String} value
  1004. * @returns {jQuery}
  1005. */
  1006. getOptionByValue: function (value) {
  1007. var options = $('option', this.$select);
  1008. var valueToCompare = value.toString();
  1009. for (var i = 0; i < options.length; i = i + 1) {
  1010. var option = options[i];
  1011. if (option.value === valueToCompare) {
  1012. return $(option);
  1013. }
  1014. }
  1015. },
  1016. /**
  1017. * Get the input (radio/checkbox) by its value.
  1018. *
  1019. * @param {String} value
  1020. * @returns {jQuery}
  1021. */
  1022. getInputByValue: function (value) {
  1023. var checkboxes = $('li input', this.$ul);
  1024. var valueToCompare = value.toString();
  1025. for (var i = 0; i < checkboxes.length; i = i + 1) {
  1026. var checkbox = checkboxes[i];
  1027. if (checkbox.value === valueToCompare) {
  1028. return $(checkbox);
  1029. }
  1030. }
  1031. },
  1032. /**
  1033. * Used for knockout integration.
  1034. */
  1035. updateOriginalOptions: function() {
  1036. this.originalOptions = this.$select.clone()[0].options;
  1037. },
  1038. asyncFunction: function(callback, timeout, self) {
  1039. var args = Array.prototype.slice.call(arguments, 3);
  1040. return setTimeout(function() {
  1041. callback.apply(self || window, args);
  1042. }, timeout);
  1043. }
  1044. };
  1045. $.fn.multiselect = function(option, parameter, extraOptions) {
  1046. return this.each(function() {
  1047. var data = $(this).data('multiselect');
  1048. var options = typeof option === 'object' && option;
  1049. // Initialize the multiselect.
  1050. if (!data) {
  1051. data = new Multiselect(this, options);
  1052. $(this).data('multiselect', data);
  1053. }
  1054. // Call multiselect method.
  1055. if (typeof option === 'string') {
  1056. data[option](parameter, extraOptions);
  1057. if (option === 'destroy') {
  1058. $(this).data('multiselect', false);
  1059. }
  1060. }
  1061. });
  1062. };
  1063. $.fn.multiselect.Constructor = Multiselect;
  1064. $(function() {
  1065. $("select[data-role=multiselect]").multiselect();
  1066. });
  1067. }(window.jQuery);