bootstrap-multiselect.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. /**
  2. * bootstrap-multiselect.js
  3. * https://github.com/davidstutz/bootstrap-multiselect
  4. *
  5. * Copyright 2012 - 2014 David Stutz
  6. *
  7. * Dual licensed under the BSD-3-Clause and the Apache License, Version 2.0.
  8. */
  9. !function($) {
  10. "use strict";// jshint ;_;
  11. if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) {
  12. ko.bindingHandlers.multiselect = {
  13. init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  14. var listOfSelectedItems = allBindingsAccessor().selectedOptions,
  15. config = ko.utils.unwrapObservable(valueAccessor());
  16. $(element).multiselect(config);
  17. if (isObservableArray(listOfSelectedItems)) {
  18. // Subscribe to the selectedOptions: ko.observableArray
  19. listOfSelectedItems.subscribe(function (changes) {
  20. var addedArray = [], deletedArray = [];
  21. changes.forEach(function (change) {
  22. switch (change.status) {
  23. case 'added':
  24. addedArray.push(change.value);
  25. break;
  26. case 'deleted':
  27. deletedArray.push(change.value);
  28. break;
  29. }
  30. });
  31. if (addedArray.length > 0) {
  32. $(element).multiselect('select', addedArray);
  33. };
  34. if (deletedArray.length > 0) {
  35. $(element).multiselect('deselect', deletedArray);
  36. };
  37. }, null, "arrayChange");
  38. }
  39. },
  40. update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  41. var listOfItems = allBindingsAccessor().options,
  42. ms = $(element).data('multiselect'),
  43. config = ko.utils.unwrapObservable(valueAccessor());
  44. if (isObservableArray(listOfItems)) {
  45. // Subscribe to the options: ko.observableArray incase it changes later
  46. listOfItems.subscribe(function (theArray) {
  47. $(element).multiselect('rebuild');
  48. });
  49. }
  50. if (!ms) {
  51. $(element).multiselect(config);
  52. }
  53. else {
  54. ms.updateOriginalOptions();
  55. }
  56. }
  57. };
  58. }
  59. function isObservableArray(obj) {
  60. return ko.isObservable(obj) && !(obj.destroyAll === undefined);
  61. }
  62. /**
  63. * Constructor to create a new multiselect using the given select.
  64. *
  65. * @param {jQuery} select
  66. * @param {Object} options
  67. * @returns {Multiselect}
  68. */
  69. function Multiselect(select, options) {
  70. this.options = this.mergeOptions(options);
  71. this.$select = $(select);
  72. // Initialization.
  73. // We have to clone to create a new reference.
  74. this.originalOptions = this.$select.clone()[0].options;
  75. this.query = '';
  76. this.searchTimeout = null;
  77. this.options.multiple = this.$select.attr('multiple') === "multiple";
  78. this.options.onChange = $.proxy(this.options.onChange, this);
  79. this.options.onDropdownShow = $.proxy(this.options.onDropdownShow, this);
  80. this.options.onDropdownHide = $.proxy(this.options.onDropdownHide, this);
  81. // Build select all if enabled.
  82. this.buildContainer();
  83. this.buildButton();
  84. this.buildSelectAll();
  85. this.buildDropdown();
  86. this.buildDropdownOptions();
  87. this.buildFilter();
  88. this.updateButtonText();
  89. this.updateSelectAll();
  90. this.$select.hide().after(this.$container);
  91. };
  92. Multiselect.prototype = {
  93. defaults: {
  94. /**
  95. * Default text function will either print 'None selected' in case no
  96. * option is selected or a list of the selected options up to a length of 3 selected options.
  97. *
  98. * @param {jQuery} options
  99. * @param {jQuery} select
  100. * @returns {String}
  101. */
  102. buttonText: function(options, select) {
  103. if (options.length === 0) {
  104. return this.nonSelectedText + ' <b class="caret"></b>';
  105. }
  106. else {
  107. if (options.length > this.numberDisplayed) {
  108. return options.length + ' ' + this.nSelectedText + ' <b class="caret"></b>';
  109. }
  110. else {
  111. var selected = '';
  112. options.each(function() {
  113. var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html();
  114. selected += label + ', ';
  115. });
  116. return selected.substr(0, selected.length - 2) + ' <b class="caret"></b>';
  117. }
  118. }
  119. },
  120. /**
  121. * Updates the title of the button similar to the buttonText function.
  122. * @param {jQuery} options
  123. * @param {jQuery} select
  124. * @returns {@exp;selected@call;substr}
  125. */
  126. buttonTitle: function(options, select) {
  127. if (options.length === 0) {
  128. return this.nonSelectedText;
  129. }
  130. else {
  131. var selected = '';
  132. options.each(function () {
  133. selected += $(this).text() + ', ';
  134. });
  135. return selected.substr(0, selected.length - 2);
  136. }
  137. },
  138. /**
  139. * Create a label.
  140. *
  141. * @param {jQuery} element
  142. * @returns {String}
  143. */
  144. label: function(element){
  145. return $(element).attr('label') || $(element).html();
  146. },
  147. /**
  148. * Triggered on change of the multiselect.
  149. * Not triggered when selecting/deselecting options manually.
  150. *
  151. * @param {jQuery} option
  152. * @param {Boolean} checked
  153. */
  154. onChange : function(option, checked) {
  155. },
  156. /**
  157. * Triggered when the dropdown is shown.
  158. *
  159. * @param {jQuery} event
  160. */
  161. onDropdownShow: function(event) {
  162. },
  163. /**
  164. * Triggered when the dropdown is hidden.
  165. *
  166. * @param {jQuery} event
  167. */
  168. onDropdownHide: function(event) {
  169. },
  170. buttonClass: 'btn btn-default',
  171. dropRight: false,
  172. selectedClass: 'active',
  173. buttonWidth: 'auto',
  174. buttonContainer: '<div class="btn-group" />',
  175. // Maximum height of the dropdown menu.
  176. // If maximum height is exceeded a scrollbar will be displayed.
  177. maxHeight: false,
  178. checkboxName: 'multiselect',
  179. includeSelectAllOption: false,
  180. includeSelectAllIfMoreThan: 0,
  181. selectAllText: ' Select all',
  182. selectAllValue: 'multiselect-all',
  183. enableFiltering: false,
  184. enableCaseInsensitiveFiltering: false,
  185. filterPlaceholder: 'Search',
  186. // possible options: 'text', 'value', 'both'
  187. filterBehavior: 'text',
  188. preventInputChangeEvent: false,
  189. nonSelectedText: 'None selected',
  190. nSelectedText: 'selected',
  191. numberDisplayed: 3,
  192. templates: {
  193. button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>',
  194. ul: '<ul class="multiselect-container dropdown-menu"></ul>',
  195. 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>',
  196. li: '<li><a href="javascript:void(0);"><label></label></a></li>',
  197. divider: '<li class="divider"></li>',
  198. liGroup: '<li><label class="multiselect-group"></label></li>'
  199. }
  200. },
  201. constructor: Multiselect,
  202. /**
  203. * Builds the container of the multiselect.
  204. */
  205. buildContainer: function() {
  206. this.$container = $(this.options.buttonContainer);
  207. this.$container.on('show.bs.dropdown', this.options.onDropdownShow);
  208. this.$container.on('hide.bs.dropdown', this.options.onDropdownHide);
  209. },
  210. /**
  211. * Builds the button of the multiselect.
  212. */
  213. buildButton: function() {
  214. this.$button = $(this.options.templates.button).addClass(this.options.buttonClass);
  215. // Adopt active state.
  216. if (this.$select.prop('disabled')) {
  217. this.disable();
  218. }
  219. else {
  220. this.enable();
  221. }
  222. // Manually add button width if set.
  223. if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') {
  224. this.$button.css({
  225. 'width' : this.options.buttonWidth
  226. });
  227. }
  228. // Keep the tab index from the select.
  229. var tabindex = this.$select.attr('tabindex');
  230. if (tabindex) {
  231. this.$button.attr('tabindex', tabindex);
  232. }
  233. this.$container.prepend(this.$button);
  234. },
  235. /**
  236. * Builds the ul representing the dropdown menu.
  237. */
  238. buildDropdown: function() {
  239. // Build ul.
  240. this.$ul = $(this.options.templates.ul);
  241. if (this.options.dropRight) {
  242. this.$ul.addClass('pull-right');
  243. }
  244. // Set max height of dropdown menu to activate auto scrollbar.
  245. if (this.options.maxHeight) {
  246. // TODO: Add a class for this option to move the css declarations.
  247. this.$ul.css({
  248. 'max-height': this.options.maxHeight + 'px',
  249. 'overflow-y': 'auto',
  250. 'overflow-x': 'hidden'
  251. });
  252. }
  253. this.$container.append(this.$ul);
  254. },
  255. /**
  256. * Build the dropdown options and binds all nessecary events.
  257. * Uses createDivider and createOptionValue to create the necessary options.
  258. */
  259. buildDropdownOptions: function() {
  260. this.$select.children().each($.proxy(function(index, element) {
  261. // Support optgroups and options without a group simultaneously.
  262. var tag = $(element).prop('tagName')
  263. .toLowerCase();
  264. if (tag === 'optgroup') {
  265. this.createOptgroup(element);
  266. }
  267. else if (tag === 'option') {
  268. if ($(element).data('role') === 'divider') {
  269. this.createDivider();
  270. }
  271. else {
  272. this.createOptionValue(element);
  273. }
  274. }
  275. // Other illegal tags will be ignored.
  276. }, this));
  277. // Bind the change event on the dropdown elements.
  278. $('li input', this.$ul).on('change', $.proxy(function(event) {
  279. var $target = $(event.target);
  280. var checked = $target.prop('checked') || false;
  281. var isSelectAllOption = $target.val() === this.options.selectAllValue;
  282. // Apply or unapply the configured selected class.
  283. if (this.options.selectedClass) {
  284. if (checked) {
  285. $target.parents('li')
  286. .addClass(this.options.selectedClass);
  287. }
  288. else {
  289. $target.parents('li')
  290. .removeClass(this.options.selectedClass);
  291. }
  292. }
  293. // Get the corresponding option.
  294. var value = $target.val();
  295. var $option = this.getOptionByValue(value);
  296. var $optionsNotThis = $('option', this.$select).not($option);
  297. var $checkboxesNotThis = $('input', this.$container).not($target);
  298. if (isSelectAllOption) {
  299. var values = [];
  300. // Select the visible checkboxes except the "select-all" and possible divider.
  301. var availableInputs = $('li input[value!="' + this.options.selectAllValue + '"][data-role!="divider"]', this.$ul).filter(':visible');
  302. for (var i = 0, j = availableInputs.length; i < j; i++) {
  303. values.push(availableInputs[i].value);
  304. }
  305. if (checked) {
  306. this.select(values);
  307. }
  308. else {
  309. this.deselect(values);
  310. }
  311. }
  312. if (checked) {
  313. $option.prop('selected', true);
  314. if (this.options.multiple) {
  315. // Simply select additional option.
  316. $option.prop('selected', true);
  317. }
  318. else {
  319. // Unselect all other options and corresponding checkboxes.
  320. if (this.options.selectedClass) {
  321. $($checkboxesNotThis).parents('li').removeClass(this.options.selectedClass);
  322. }
  323. $($checkboxesNotThis).prop('checked', false);
  324. $optionsNotThis.prop('selected', false);
  325. // It's a single selection, so close.
  326. this.$button.click();
  327. }
  328. if (this.options.selectedClass === "active") {
  329. $optionsNotThis.parents("a").css("outline", "");
  330. }
  331. }
  332. else {
  333. // Unselect option.
  334. $option.prop('selected', false);
  335. }
  336. this.$select.change();
  337. this.options.onChange($option, checked);
  338. this.updateButtonText();
  339. this.updateSelectAll();
  340. if(this.options.preventInputChangeEvent) {
  341. return false;
  342. }
  343. }, this));
  344. $('li a', this.$ul).on('touchstart click', function(event) {
  345. event.stopPropagation();
  346. var $target = $(event.target);
  347. if (event.shiftKey) {
  348. var checked = $target.prop('checked') || false;
  349. if (checked) {
  350. var prev = $target.parents('li:last')
  351. .siblings('li[class="active"]:first');
  352. var currentIdx = $target.parents('li')
  353. .index();
  354. var prevIdx = prev.index();
  355. if (currentIdx > prevIdx) {
  356. $target.parents("li:last").prevUntil(prev).each(
  357. function() {
  358. $(this).find("input:first").prop("checked", true)
  359. .trigger("change");
  360. }
  361. );
  362. }
  363. else {
  364. $target.parents("li:last").nextUntil(prev).each(
  365. function() {
  366. $(this).find("input:first").prop("checked", true)
  367. .trigger("change");
  368. }
  369. );
  370. }
  371. }
  372. }
  373. $target.blur();
  374. });
  375. // Keyboard support.
  376. this.$container.on('keydown', $.proxy(function(event) {
  377. if ($('input[type="text"]', this.$container).is(':focus')) {
  378. return;
  379. }
  380. if ((event.keyCode === 9 || event.keyCode === 27)
  381. && this.$container.hasClass('open')) {
  382. // Close on tab or escape.
  383. this.$button.click();
  384. }
  385. else {
  386. var $items = $(this.$container).find("li:not(.divider):visible a");
  387. if (!$items.length) {
  388. return;
  389. }
  390. var index = $items.index($items.filter(':focus'));
  391. // Navigation up.
  392. if (event.keyCode === 38 && index > 0) {
  393. index--;
  394. }
  395. // Navigate down.
  396. else if (event.keyCode === 40 && index < $items.length - 1) {
  397. index++;
  398. }
  399. else if (!~index) {
  400. index = 0;
  401. }
  402. var $current = $items.eq(index);
  403. $current.focus();
  404. if (event.keyCode === 32 || event.keyCode === 13) {
  405. var $checkbox = $current.find('input');
  406. $checkbox.prop("checked", !$checkbox.prop("checked"));
  407. $checkbox.change();
  408. }
  409. event.stopPropagation();
  410. event.preventDefault();
  411. }
  412. }, this));
  413. },
  414. /**
  415. * Create an option using the given select option.
  416. *
  417. * @param {jQuery} element
  418. */
  419. createOptionValue: function(element) {
  420. if ($(element).is(':selected')) {
  421. $(element).prop('selected', true);
  422. }
  423. // Support the label attribute on options.
  424. var label = this.options.label(element);
  425. var value = $(element).val();
  426. var inputType = this.options.multiple ? "checkbox" : "radio";
  427. var $li = $(this.options.templates.li);
  428. $('label', $li).addClass(inputType);
  429. $('label', $li).append('<input type="' + inputType + '" name="' + this.options.checkboxName + '" />');
  430. var selected = $(element).prop('selected') || false;
  431. var $checkbox = $('input', $li);
  432. $checkbox.val(value);
  433. if (value === this.options.selectAllValue) {
  434. $checkbox.parent().parent()
  435. .addClass('multiselect-all');
  436. }
  437. $('label', $li).append(" " + label);
  438. this.$ul.append($li);
  439. if ($(element).is(':disabled')) {
  440. $checkbox.attr('disabled', 'disabled')
  441. .prop('disabled', true)
  442. .parents('li')
  443. .addClass('disabled');
  444. }
  445. $checkbox.prop('checked', selected);
  446. if (selected && this.options.selectedClass) {
  447. $checkbox.parents('li')
  448. .addClass(this.options.selectedClass);
  449. }
  450. },
  451. /**
  452. * Creates a divider using the given select option.
  453. *
  454. * @param {jQuery} element
  455. */
  456. createDivider: function(element) {
  457. var $divider = $(this.options.templates.divider);
  458. this.$ul.append($divider);
  459. },
  460. /**
  461. * Creates an optgroup.
  462. *
  463. * @param {jQuery} group
  464. */
  465. createOptgroup: function(group) {
  466. var groupName = $(group).prop('label');
  467. // Add a header for the group.
  468. var $li = $(this.options.templates.liGroup);
  469. $('label', $li).text(groupName);
  470. this.$ul.append($li);
  471. if ($(group).is(':disabled')) {
  472. $li.addClass('disabled');
  473. }
  474. // Add the options of the group.
  475. $('option', group).each($.proxy(function(index, element) {
  476. this.createOptionValue(element);
  477. }, this));
  478. },
  479. /**
  480. * Build the selct all.
  481. * Checks if a select all ahs already been created.
  482. */
  483. buildSelectAll: function() {
  484. var alreadyHasSelectAll = this.hasSelectAll();
  485. if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple
  486. && $('option[data-role!="divider"]', this.$select).length > this.options.includeSelectAllIfMoreThan) {
  487. // Check whether to add a divider after the select all.
  488. if (this.options.includeSelectAllDivider) {
  489. this.$select.prepend('<option value="" disabled="disabled" data-role="divider">');
  490. }
  491. this.$select.prepend('<option value="' + this.options.selectAllValue + '">' + this.options.selectAllText + '</option>');
  492. }
  493. },
  494. /**
  495. * Builds the filter.
  496. */
  497. buildFilter: function() {
  498. // Build filter if filtering OR case insensitive filtering is enabled and the number of options exceeds (or equals) enableFilterLength.
  499. if (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering) {
  500. var enableFilterLength = Math.max(this.options.enableFiltering, this.options.enableCaseInsensitiveFiltering);
  501. if (this.$select.find('option').length >= enableFilterLength) {
  502. this.$filter = $(this.options.templates.filter);
  503. $('input', this.$filter).attr('placeholder', this.options.filterPlaceholder);
  504. this.$ul.prepend(this.$filter);
  505. this.$filter.val(this.query).on('click', function(event) {
  506. event.stopPropagation();
  507. }).on('input keydown', $.proxy(function(event) {
  508. // This is useful to catch "keydown" events after the browser has updated the control.
  509. clearTimeout(this.searchTimeout);
  510. this.searchTimeout = this.asyncFunction($.proxy(function() {
  511. if (this.query !== event.target.value) {
  512. this.query = event.target.value;
  513. $.each($('li', this.$ul), $.proxy(function(index, element) {
  514. var value = $('input', element).val();
  515. var text = $('label', element).text();
  516. var filterCandidate = '';
  517. if ((this.options.filterBehavior === 'text')) {
  518. filterCandidate = text;
  519. }
  520. else if ((this.options.filterBehavior === 'value')) {
  521. filterCandidate = value;
  522. }
  523. else if (this.options.filterBehavior === 'both') {
  524. filterCandidate = text + '\n' + value;
  525. }
  526. if (value !== this.options.selectAllValue && text) {
  527. // by default lets assume that element is not
  528. // interesting for this search
  529. var showElement = false;
  530. if (this.options.enableCaseInsensitiveFiltering && filterCandidate.toLowerCase().indexOf(this.query.toLowerCase()) > -1) {
  531. showElement = true;
  532. }
  533. else if (filterCandidate.indexOf(this.query) > -1) {
  534. showElement = true;
  535. }
  536. if (showElement) {
  537. $(element).show();
  538. }
  539. else {
  540. $(element).hide();
  541. }
  542. }
  543. }, this));
  544. }
  545. // TODO: check whether select all option needs to be updated.
  546. }, this), 300, this);
  547. }, this));
  548. }
  549. }
  550. },
  551. /**
  552. * Unbinds the whole plugin.
  553. */
  554. destroy: function() {
  555. this.$container.remove();
  556. this.$select.show();
  557. this.$select.data('multiselect', null);
  558. },
  559. /**
  560. * Refreshs the multiselect based on the selected options of the select.
  561. */
  562. refresh: function() {
  563. $('option', this.$select).each($.proxy(function(index, element) {
  564. var $input = $('li input', this.$ul).filter(function() {
  565. return $(this).val() === $(element).val();
  566. });
  567. if ($(element).is(':selected')) {
  568. $input.prop('checked', true);
  569. if (this.options.selectedClass) {
  570. $input.parents('li')
  571. .addClass(this.options.selectedClass);
  572. }
  573. }
  574. else {
  575. $input.prop('checked', false);
  576. if (this.options.selectedClass) {
  577. $input.parents('li')
  578. .removeClass(this.options.selectedClass);
  579. }
  580. }
  581. if ($(element).is(":disabled")) {
  582. $input.attr('disabled', 'disabled')
  583. .prop('disabled', true)
  584. .parents('li')
  585. .addClass('disabled');
  586. }
  587. else {
  588. $input.prop('disabled', false)
  589. .parents('li')
  590. .removeClass('disabled');
  591. }
  592. }, this));
  593. this.updateButtonText();
  594. this.updateSelectAll();
  595. },
  596. /**
  597. * Select all options of the given values.
  598. *
  599. * @param {Array} selectValues
  600. */
  601. select: function(selectValues) {
  602. if(!$.isArray(selectValues)) {
  603. selectValues = [selectValues];
  604. }
  605. for (var i = 0; i < selectValues.length; i++) {
  606. var value = selectValues[i];
  607. var $option = this.getOptionByValue(value);
  608. var $checkbox = this.getInputByValue(value);
  609. if (this.options.selectedClass) {
  610. $checkbox.parents('li')
  611. .addClass(this.options.selectedClass);
  612. }
  613. $checkbox.prop('checked', true);
  614. $option.prop('selected', true);
  615. }
  616. this.updateButtonText();
  617. },
  618. /**
  619. * Clears all selected items
  620. *
  621. */
  622. clearSelection: function () {
  623. var selected = this.getSelected();
  624. if (selected.length) {
  625. var arry = [];
  626. for (var i = 0; i < selected.length; i = i + 1) {
  627. arry.push(selected[i].value);
  628. }
  629. this.deselect(arry);
  630. this.$select.change();
  631. }
  632. },
  633. /**
  634. * Deselects all options of the given values.
  635. *
  636. * @param {Array} deselectValues
  637. */
  638. deselect: function(deselectValues) {
  639. if(!$.isArray(deselectValues)) {
  640. deselectValues = [deselectValues];
  641. }
  642. for (var i = 0; i < deselectValues.length; i++) {
  643. var value = deselectValues[i];
  644. var $option = this.getOptionByValue(value);
  645. var $checkbox = this.getInputByValue(value);
  646. if (this.options.selectedClass) {
  647. $checkbox.parents('li')
  648. .removeClass(this.options.selectedClass);
  649. }
  650. $checkbox.prop('checked', false);
  651. $option.prop('selected', false);
  652. }
  653. this.updateButtonText();
  654. },
  655. /**
  656. * Rebuild the plugin.
  657. * Rebuilds the dropdown, the filter and the select all option.
  658. */
  659. rebuild: function() {
  660. this.$ul.html('');
  661. // Remove select all option in select.
  662. $('option[value="' + this.options.selectAllValue + '"]', this.$select).remove();
  663. // Important to distinguish between radios and checkboxes.
  664. this.options.multiple = this.$select.attr('multiple') === "multiple";
  665. this.buildSelectAll();
  666. this.buildDropdownOptions();
  667. this.buildFilter();
  668. this.updateButtonText();
  669. this.updateSelectAll();
  670. },
  671. /**
  672. * The provided data will be used to build the dropdown.
  673. *
  674. * @param {Array} dataprovider
  675. */
  676. dataprovider: function(dataprovider) {
  677. var optionDOM = "";
  678. dataprovider.forEach(function (option) {
  679. optionDOM += '<option value="' + option.value + '">' + option.label + '</option>';
  680. });
  681. this.$select.html(optionDOM);
  682. this.rebuild();
  683. },
  684. /**
  685. * Enable the multiselect.
  686. */
  687. enable: function() {
  688. this.$select.prop('disabled', false);
  689. this.$button.prop('disabled', false)
  690. .removeClass('disabled');
  691. },
  692. /**
  693. * Disable the multiselect.
  694. */
  695. disable: function() {
  696. this.$select.prop('disabled', true);
  697. this.$button.prop('disabled', true)
  698. .addClass('disabled');
  699. },
  700. /**
  701. * Set the options.
  702. *
  703. * @param {Array} options
  704. */
  705. setOptions: function(options) {
  706. this.options = this.mergeOptions(options);
  707. },
  708. /**
  709. * Merges the given options with the default options.
  710. *
  711. * @param {Array} options
  712. * @returns {Array}
  713. */
  714. mergeOptions: function(options) {
  715. return $.extend(true, {}, this.defaults, options);
  716. },
  717. /**
  718. * Checks whether a select all option is present.
  719. *
  720. * @returns {Boolean}
  721. */
  722. hasSelectAll: function() {
  723. return $('option[value="' + this.options.selectAllValue + '"]', this.$select).length > 0;
  724. },
  725. /**
  726. * Updates the select all option based on the currently selected options.
  727. */
  728. updateSelectAll: function() {
  729. if (this.hasSelectAll()) {
  730. var selected = this.getSelected();
  731. if (selected.length === $('option:not([data-role=divider])', this.$select).length - 1) {
  732. this.select(this.options.selectAllValue);
  733. }
  734. else {
  735. this.deselect(this.options.selectAllValue);
  736. }
  737. }
  738. },
  739. /**
  740. * Update the button text and its title based on the currently selected options.
  741. */
  742. updateButtonText: function() {
  743. var options = this.getSelected();
  744. // First update the displayed button text.
  745. $('button', this.$container).html(this.options.buttonText(options, this.$select));
  746. // Now update the title attribute of the button.
  747. $('button', this.$container).attr('title', this.options.buttonTitle(options, this.$select));
  748. },
  749. /**
  750. * Get all selected options.
  751. *
  752. * @returns {jQUery}
  753. */
  754. getSelected: function() {
  755. return $('option[value!="' + this.options.selectAllValue + '"]:selected', this.$select).filter(function() {
  756. return $(this).prop('selected');
  757. });
  758. },
  759. /**
  760. * Gets a select option by its value.
  761. *
  762. * @param {String} value
  763. * @returns {jQuery}
  764. */
  765. getOptionByValue: function (value) {
  766. var options = $('option', this.$select);
  767. var valueToCompare = value.toString();
  768. for (var i = 0; i < options.length; i = i + 1) {
  769. var option = options[i];
  770. if (option.value === valueToCompare) {
  771. return $(option);
  772. }
  773. }
  774. },
  775. /**
  776. * Get the input (radio/checkbox) by its value.
  777. *
  778. * @param {String} value
  779. * @returns {jQuery}
  780. */
  781. getInputByValue: function (value) {
  782. var checkboxes = $('li input', this.$ul);
  783. var valueToCompare = value.toString();
  784. for (var i = 0; i < checkboxes.length; i = i + 1) {
  785. var checkbox = checkboxes[i];
  786. if (checkbox.value === valueToCompare) {
  787. return $(checkbox);
  788. }
  789. }
  790. },
  791. /**
  792. * Used for knockout integration.
  793. */
  794. updateOriginalOptions: function() {
  795. this.originalOptions = this.$select.clone()[0].options;
  796. },
  797. asyncFunction: function(callback, timeout, self) {
  798. var args = Array.prototype.slice.call(arguments, 3);
  799. return setTimeout(function() {
  800. callback.apply(self || window, args);
  801. }, timeout);
  802. }
  803. };
  804. $.fn.multiselect = function(option, parameter) {
  805. return this.each(function() {
  806. var data = $(this).data('multiselect');
  807. var options = typeof option === 'object' && option;
  808. // Initialize the multiselect.
  809. if (!data) {
  810. data = new Multiselect(this, options);
  811. $(this).data('multiselect', data);
  812. }
  813. // Call multiselect method.
  814. if (typeof option === 'string') {
  815. data[option](parameter);
  816. if (option === 'destroy') {
  817. $(this).data('multiselect', false);
  818. }
  819. }
  820. });
  821. };
  822. $.fn.multiselect.Constructor = Multiselect;
  823. $(function() {
  824. $("select[data-role=multiselect]").multiselect();
  825. });
  826. }(window.jQuery);