bootstrap_multiselect.js 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  1. /**
  2. * Bootstrap Multiselect (https://github.com/davidstutz/bootstrap-multiselect)
  3. *
  4. * Apache License, Version 2.0:
  5. * Copyright (c) 2012 - 2015 David Stutz
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  8. * use this file except in compliance with the License. You may obtain a
  9. * copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. * License for the specific language governing permissions and limitations
  15. * under the License.
  16. *
  17. * BSD 3-Clause License:
  18. * Copyright (c) 2012 - 2015 David Stutz
  19. * All rights reserved.
  20. *
  21. * Redistribution and use in source and binary forms, with or without
  22. * modification, are permitted provided that the following conditions are met:
  23. * - Redistributions of source code must retain the above copyright notice,
  24. * this list of conditions and the following disclaimer.
  25. * - Redistributions in binary form must reproduce the above copyright notice,
  26. * this list of conditions and the following disclaimer in the documentation
  27. * and/or other materials provided with the distribution.
  28. * - Neither the name of David Stutz nor the names of its contributors may be
  29. * used to endorse or promote products derived from this software without
  30. * specific prior written permission.
  31. *
  32. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  33. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  34. * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  35. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  36. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  37. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  38. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  39. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  40. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  41. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. !function ($) {
  45. "use strict";// jshint ;_;
  46. if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) {
  47. ko.bindingHandlers.multiselect = {
  48. after: ['options', 'value', 'selectedOptions', 'enable', 'disable'],
  49. init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  50. var $element = $(element);
  51. var config = ko.toJS(valueAccessor());
  52. $element.multiselect(config);
  53. if (allBindings.has('options')) {
  54. var options = allBindings.get('options');
  55. if (ko.isObservable(options)) {
  56. ko.computed({
  57. read: function() {
  58. options();
  59. setTimeout(function() {
  60. var ms = $element.data('multiselect');
  61. if (ms)
  62. ms.updateOriginalOptions();//Not sure how beneficial this is.
  63. $element.multiselect('rebuild');
  64. }, 1);
  65. },
  66. disposeWhenNodeIsRemoved: element
  67. });
  68. }
  69. }
  70. //value and selectedOptions are two-way, so these will be triggered even by our own actions.
  71. //It needs some way to tell if they are triggered because of us or because of outside change.
  72. //It doesn't loop but it's a waste of processing.
  73. if (allBindings.has('value')) {
  74. var value = allBindings.get('value');
  75. if (ko.isObservable(value)) {
  76. ko.computed({
  77. read: function() {
  78. value();
  79. setTimeout(function() {
  80. $element.multiselect('refresh');
  81. }, 1);
  82. },
  83. disposeWhenNodeIsRemoved: element
  84. }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
  85. }
  86. }
  87. //Switched from arrayChange subscription to general subscription using 'refresh'.
  88. //Not sure performance is any better using 'select' and 'deselect'.
  89. if (allBindings.has('selectedOptions')) {
  90. var selectedOptions = allBindings.get('selectedOptions');
  91. if (ko.isObservable(selectedOptions)) {
  92. ko.computed({
  93. read: function() {
  94. selectedOptions();
  95. setTimeout(function() {
  96. $element.multiselect('refresh');
  97. }, 1);
  98. },
  99. disposeWhenNodeIsRemoved: element
  100. }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
  101. }
  102. }
  103. var setEnabled = function (enable) {
  104. setTimeout(function () {
  105. if (enable)
  106. $element.multiselect('enable');
  107. else
  108. $element.multiselect('disable');
  109. });
  110. };
  111. if (allBindings.has('enable')) {
  112. var enable = allBindings.get('enable');
  113. if (ko.isObservable(enable)) {
  114. ko.computed({
  115. read: function () {
  116. setEnabled(enable());
  117. },
  118. disposeWhenNodeIsRemoved: element
  119. }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
  120. } else {
  121. setEnabled(enable);
  122. }
  123. }
  124. if (allBindings.has('disable')) {
  125. var disable = allBindings.get('disable');
  126. if (ko.isObservable(disable)) {
  127. ko.computed({
  128. read: function () {
  129. setEnabled(!disable());
  130. },
  131. disposeWhenNodeIsRemoved: element
  132. }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
  133. } else {
  134. setEnabled(!disable);
  135. }
  136. }
  137. ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
  138. $element.multiselect('destroy');
  139. });
  140. },
  141. update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
  142. var $element = $(element);
  143. var config = ko.toJS(valueAccessor());
  144. $element.multiselect('setOptions', config);
  145. $element.multiselect('rebuild');
  146. }
  147. };
  148. }
  149. function forEach(array, callback) {
  150. for (var index = 0; index < array.length; ++index) {
  151. callback(array[index], index);
  152. }
  153. }
  154. /**
  155. * Constructor to create a new multiselect using the given select.
  156. *
  157. * @param {jQuery} select
  158. * @param {Object} options
  159. * @returns {Multiselect}
  160. */
  161. function Multiselect(select, options) {
  162. this.$select = $(select);
  163. this.options = this.mergeOptions($.extend({}, options, this.$select.data()));
  164. // Placeholder via data attributes
  165. if (this.$select.attr("data-placeholder")) {
  166. this.options.nonSelectedText = this.$select.data("placeholder");
  167. }
  168. // Button width via data attributes
  169. if (this.$select.attr("data-button-width")) {
  170. this.options.buttonWidth = this.$select.data("button-width");
  171. }
  172. // Initialization.
  173. // We have to clone to create a new reference.
  174. this.originalOptions = this.$select.clone()[0].options;
  175. this.query = '';
  176. this.searchTimeout = null;
  177. this.lastToggledInput = null;
  178. this.options.multiple = this.$select.attr('multiple') === "multiple";
  179. this.options.onChange = $.proxy(this.options.onChange, this);
  180. this.options.onSelectAll = $.proxy(this.options.onSelectAll, this);
  181. this.options.onDeselectAll = $.proxy(this.options.onDeselectAll, this);
  182. this.options.onDropdownShow = $.proxy(this.options.onDropdownShow, this);
  183. this.options.onDropdownHide = $.proxy(this.options.onDropdownHide, this);
  184. this.options.onDropdownShown = $.proxy(this.options.onDropdownShown, this);
  185. this.options.onDropdownHidden = $.proxy(this.options.onDropdownHidden, this);
  186. this.options.onInitialized = $.proxy(this.options.onInitialized, this);
  187. this.options.onFiltering = $.proxy(this.options.onFiltering, this);
  188. // Build select all if enabled.
  189. this.buildContainer();
  190. this.buildButton();
  191. this.buildDropdown();
  192. this.buildSelectAll();
  193. this.buildDropdownOptions();
  194. this.buildFilter();
  195. this.updateButtonText();
  196. this.updateSelectAll(true);
  197. if (this.options.enableClickableOptGroups && this.options.multiple) {
  198. this.updateOptGroups();
  199. }
  200. this.options.wasDisabled = this.$select.prop('disabled');
  201. if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) {
  202. this.disable();
  203. }
  204. this.$select.wrap('<div class="multiselect-native-select" />').after(this.$container);
  205. this.options.onInitialized(this.$select, this.$container);
  206. }
  207. Multiselect.prototype = {
  208. defaults: {
  209. /**
  210. * Default text function will either print 'None selected' in case no
  211. * option is selected or a list of the selected options up to a length
  212. * of 3 selected options.
  213. *
  214. * @param {jQuery} options
  215. * @param {jQuery} select
  216. * @returns {String}
  217. */
  218. buttonText: function(options, select) {
  219. if (this.disabledText.length > 0
  220. && (select.prop('disabled') || (options.length == 0 && this.disableIfEmpty))) {
  221. return this.disabledText;
  222. }
  223. else if (options.length === 0) {
  224. return this.nonSelectedText;
  225. }
  226. else if (this.allSelectedText
  227. && options.length === $('option', $(select)).length
  228. && $('option', $(select)).length !== 1
  229. && this.multiple) {
  230. if (this.selectAllNumber) {
  231. return this.allSelectedText + ' (' + options.length + ')';
  232. }
  233. else {
  234. return this.allSelectedText;
  235. }
  236. }
  237. else if (options.length > this.numberDisplayed) {
  238. return options.length + ' ' + this.nSelectedText;
  239. }
  240. else {
  241. var selected = '';
  242. var delimiter = this.delimiterText;
  243. options.each(function() {
  244. var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text();
  245. selected += label + delimiter;
  246. });
  247. return selected.substr(0, selected.length - this.delimiterText.length);
  248. }
  249. },
  250. /**
  251. * Updates the title of the button similar to the buttonText function.
  252. *
  253. * @param {jQuery} options
  254. * @param {jQuery} select
  255. * @returns {@exp;selected@call;substr}
  256. */
  257. buttonTitle: function(options, select) {
  258. if (options.length === 0) {
  259. return this.nonSelectedText;
  260. }
  261. else {
  262. var selected = '';
  263. var delimiter = this.delimiterText;
  264. options.each(function () {
  265. var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text();
  266. selected += label + delimiter;
  267. });
  268. return selected.substr(0, selected.length - this.delimiterText.length);
  269. }
  270. },
  271. checkboxName: function(option) {
  272. return false; // no checkbox name
  273. },
  274. /**
  275. * Create a label.
  276. *
  277. * @param {jQuery} element
  278. * @returns {String}
  279. */
  280. optionLabel: function(element){
  281. return $(element).attr('label') || $(element).text();
  282. },
  283. /**
  284. * Create a class.
  285. *
  286. * @param {jQuery} element
  287. * @returns {String}
  288. */
  289. optionClass: function(element) {
  290. return $(element).attr('class') || '';
  291. },
  292. /**
  293. * Triggered on change of the multiselect.
  294. *
  295. * Not triggered when selecting/deselecting options manually.
  296. *
  297. * @param {jQuery} option
  298. * @param {Boolean} checked
  299. */
  300. onChange : function(option, checked) {
  301. },
  302. /**
  303. * Triggered when the dropdown is shown.
  304. *
  305. * @param {jQuery} event
  306. */
  307. onDropdownShow: function(event) {
  308. },
  309. /**
  310. * Triggered when the dropdown is hidden.
  311. *
  312. * @param {jQuery} event
  313. */
  314. onDropdownHide: function(event) {
  315. },
  316. /**
  317. * Triggered after the dropdown is shown.
  318. *
  319. * @param {jQuery} event
  320. */
  321. onDropdownShown: function(event) {
  322. },
  323. /**
  324. * Triggered after the dropdown is hidden.
  325. *
  326. * @param {jQuery} event
  327. */
  328. onDropdownHidden: function(event) {
  329. },
  330. /**
  331. * Triggered on select all.
  332. */
  333. onSelectAll: function() {
  334. },
  335. /**
  336. * Triggered on deselect all.
  337. */
  338. onDeselectAll: function() {
  339. },
  340. /**
  341. * Triggered after initializing.
  342. *
  343. * @param {jQuery} $select
  344. * @param {jQuery} $container
  345. */
  346. onInitialized: function($select, $container) {
  347. },
  348. /**
  349. * Triggered on filtering.
  350. *
  351. * @param {jQuery} $filter
  352. */
  353. onFiltering: function($filter) {
  354. },
  355. enableHTML: true,
  356. buttonClass: 'btn btn-light',
  357. inheritClass: false,
  358. buttonWidth: '100%',
  359. buttonContainer: '<div class="btn-group" />',
  360. dropRight: false,
  361. dropUp: false,
  362. selectedClass: 'active',
  363. // Maximum height of the dropdown menu.
  364. // If maximum height is exceeded a scrollbar will be displayed.
  365. maxHeight: false,
  366. includeSelectAllOption: false,
  367. includeSelectAllIfMoreThan: 0,
  368. selectAllText: ' Select all',
  369. selectAllValue: 'multiselect-all',
  370. selectAllName: false,
  371. selectAllNumber: true,
  372. selectAllJustVisible: true,
  373. enableFiltering: false,
  374. enableCaseInsensitiveFiltering: false,
  375. enableFullValueFiltering: false,
  376. enableClickableOptGroups: false,
  377. enableCollapsibleOptGroups: false,
  378. filterPlaceholder: 'Search',
  379. // possible options: 'text', 'value', 'both'
  380. filterBehavior: 'text',
  381. includeFilterClearBtn: true,
  382. preventInputChangeEvent: false,
  383. nonSelectedText: 'None selected',
  384. nSelectedText: 'selected',
  385. allSelectedText: 'All selected',
  386. numberDisplayed: 3,
  387. disableIfEmpty: false,
  388. disabledText: '',
  389. delimiterText: ', ',
  390. templates: {
  391. button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"><span class="multiselect-selected-text"></span></button>',
  392. ul: '<div class="multiselect-container dropdown-menu"></div>',
  393. filter: '<div class="multiselect-item multiselect-filter"><div class="input-group"><input class="form-control multiselect-search" type="text"><i class="icon-search4"></i></div></div>',
  394. filterClearBtn: '<span class="input-group-append"><button class="btn btn-light btn-icon multiselect-clear-filter" type="button"><i class="icon-cross2"></i></button></span>',
  395. li: '<div class="multiselect-item dropdown-item form-check" tabindex="0"><label class="form-check-label"></label></div>',
  396. divider: '<div class="multiselect-item dropdown-divider"></div>',
  397. liGroup: '<div class="multiselect-item multiselect-group"><label class="form-check-label"></label></div>'
  398. }
  399. },
  400. constructor: Multiselect,
  401. /**
  402. * Builds the container of the multiselect.
  403. */
  404. buildContainer: function() {
  405. this.$container = $(this.options.buttonContainer);
  406. this.$container.on('show.bs.dropdown', this.options.onDropdownShow);
  407. this.$container.on('hide.bs.dropdown', this.options.onDropdownHide);
  408. this.$container.on('shown.bs.dropdown', this.options.onDropdownShown);
  409. this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden);
  410. },
  411. /**
  412. * Builds the button of the multiselect.
  413. */
  414. buildButton: function() {
  415. this.$button = $(this.options.templates.button).addClass(this.options.buttonClass);
  416. if (this.$select.attr('class') && this.options.inheritClass) {
  417. this.$button.addClass(this.$select.attr('class'));
  418. }
  419. // Adopt active state.
  420. if (this.$select.prop('disabled')) {
  421. this.disable();
  422. }
  423. else {
  424. this.enable();
  425. }
  426. // Manually add button width if set.
  427. if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') {
  428. this.$button.css({
  429. 'width' : '100%', //this.options.buttonWidth,
  430. 'overflow' : 'hidden',
  431. 'text-overflow' : 'ellipsis'
  432. });
  433. this.$container.css({
  434. 'width': this.options.buttonWidth
  435. });
  436. }
  437. // Keep the tab index from the select.
  438. var tabindex = this.$select.attr('tabindex');
  439. if (tabindex) {
  440. this.$button.attr('tabindex', tabindex);
  441. }
  442. this.$container.prepend(this.$button);
  443. },
  444. /**
  445. * Builds the ul representing the dropdown menu.
  446. */
  447. buildDropdown: function() {
  448. // Build ul.
  449. this.$ul = $(this.options.templates.ul);
  450. if (this.options.dropRight) {
  451. this.$ul.addClass('dropdown-menu-right');
  452. }
  453. // Set max height of dropdown menu to activate auto scrollbar.
  454. if (this.options.maxHeight) {
  455. // TODO: Add a class for this option to move the css declarations.
  456. this.$ul.css({
  457. 'max-height': this.options.maxHeight + 'px',
  458. 'overflow-y': 'auto',
  459. 'overflow-x': 'hidden'
  460. });
  461. }
  462. if (this.options.dropUp) {
  463. var height = Math.min(this.options.maxHeight, $('option[data-role!="divider"]', this.$select).length*26 + $('option[data-role="divider"]', this.$select).length*19 + (this.options.includeSelectAllOption ? 26 : 0) + (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering ? 44 : 0));
  464. var moveCalc = height + 34;
  465. this.$ul.css({
  466. 'max-height': height + 'px',
  467. 'overflow-y': 'auto',
  468. 'overflow-x': 'hidden',
  469. 'margin-top': "-" + moveCalc + 'px'
  470. });
  471. }
  472. this.$container.append(this.$ul);
  473. },
  474. /**
  475. * Build the dropdown options and binds all necessary events.
  476. *
  477. * Uses createDivider and createOptionValue to create the necessary options.
  478. */
  479. buildDropdownOptions: function() {
  480. this.$select.children().each($.proxy(function(index, element) {
  481. var $element = $(element);
  482. // Support optgroups and options without a group simultaneously.
  483. var tag = $element.prop('tagName')
  484. .toLowerCase();
  485. if ($element.prop('value') === this.options.selectAllValue) {
  486. return;
  487. }
  488. if (tag === 'optgroup') {
  489. this.createOptgroup(element);
  490. }
  491. else if (tag === 'option') {
  492. if ($element.data('role') === 'divider') {
  493. this.createDivider();
  494. }
  495. else {
  496. this.createOptionValue(element);
  497. }
  498. }
  499. // Other illegal tags will be ignored.
  500. }, this));
  501. // Bind the change event on the dropdown elements.
  502. $('.multiselect-item:not(.multiselect-group) input', this.$ul).on('change', $.proxy(function(event) {
  503. var $target = $(event.target);
  504. var checked = $target.prop('checked') || false;
  505. var isSelectAllOption = $target.val() === this.options.selectAllValue;
  506. // Apply or unapply the configured selected class.
  507. if (this.options.selectedClass) {
  508. if (checked) {
  509. $target.closest('.multiselect-item')
  510. .addClass(this.options.selectedClass);
  511. }
  512. else {
  513. $target.closest('.multiselect-item')
  514. .removeClass(this.options.selectedClass);
  515. }
  516. }
  517. // Get the corresponding option.
  518. var value = $target.val();
  519. var $option = this.getOptionByValue(value);
  520. var $optionsNotThis = $('option', this.$select).not($option);
  521. var $checkboxesNotThis = $('input', this.$container).not($target);
  522. if (isSelectAllOption) {
  523. if (checked) {
  524. this.selectAll(this.options.selectAllJustVisible, true);
  525. }
  526. else {
  527. this.deselectAll(this.options.selectAllJustVisible, true);
  528. }
  529. }
  530. else {
  531. if (checked) {
  532. $option.prop('selected', true);
  533. if (this.options.multiple) {
  534. // Simply select additional option.
  535. $option.prop('selected', true);
  536. }
  537. else {
  538. // Unselect all other options and corresponding checkboxes.
  539. if (this.options.selectedClass) {
  540. $($checkboxesNotThis).closest('.multiselect-item').removeClass(this.options.selectedClass);
  541. }
  542. $($checkboxesNotThis).prop('checked', false);
  543. $optionsNotThis.prop('selected', false);
  544. // It's a single selection, so close.
  545. this.$button.click();
  546. }
  547. // if (this.options.selectedClass === "active") {
  548. // $optionsNotThis.closest("a").css("outline", "");
  549. // }
  550. }
  551. else {
  552. // Unselect option.
  553. $option.prop('selected', false);
  554. }
  555. // To prevent select all from firing onChange: #575
  556. this.options.onChange($option, checked);
  557. // Do not update select all or optgroups on select all change!
  558. this.updateSelectAll();
  559. if (this.options.enableClickableOptGroups && this.options.multiple) {
  560. this.updateOptGroups();
  561. }
  562. }
  563. this.$select.change();
  564. this.updateButtonText();
  565. if(this.options.preventInputChangeEvent) {
  566. return false;
  567. }
  568. }, this));
  569. $('.dropdown-item', this.$ul).on('mousedown', function(e) {
  570. if (e.shiftKey) {
  571. // Prevent selecting text by Shift+click
  572. return false;
  573. }
  574. });
  575. $('.dropdown-item', this.$ul).on('touchstart click', $.proxy(function(event) {
  576. event.stopPropagation();
  577. var $target = $(event.target);
  578. if (event.shiftKey && this.options.multiple) {
  579. if($target.is("label")){ // Handles checkbox selection manually (see https://github.com/davidstutz/bootstrap-multiselect/issues/431)
  580. event.preventDefault();
  581. $target = $target.find("input");
  582. $target.prop("checked", !$target.prop("checked"));
  583. }
  584. var checked = $target.prop('checked') || false;
  585. if (this.lastToggledInput !== null && this.lastToggledInput !== $target) { // Make sure we actually have a range
  586. var from = $target.closest(".multiselect-item").index();
  587. var to = this.lastToggledInput.closest(".multiselect-item").index();
  588. if (from > to) { // Swap the indices
  589. var tmp = to;
  590. to = from;
  591. from = tmp;
  592. }
  593. // Make sure we grab all elements since slice excludes the last index
  594. ++to;
  595. // Change the checkboxes and underlying options
  596. var range = this.$ul.find(".multiselect-item").slice(from, to).find("input");
  597. range.prop('checked', checked);
  598. if (this.options.selectedClass) {
  599. range.closest('.multiselect-item')
  600. .toggleClass(this.options.selectedClass, checked);
  601. }
  602. for (var i = 0, j = range.length; i < j; i++) {
  603. var $checkbox = $(range[i]);
  604. var $option = this.getOptionByValue($checkbox.val());
  605. $option.prop('selected', checked);
  606. }
  607. }
  608. // Trigger the select "change" event
  609. $target.trigger("change");
  610. }
  611. // Remembers last clicked option
  612. if($target.is("input") && !$target.closest("div, a").is(".multiselect-item")){
  613. this.lastToggledInput = $target;
  614. }
  615. $target.blur();
  616. }, this));
  617. // Keyboard support.
  618. this.$container.off('keydown.multiselect').on('keydown.multiselect', $.proxy(function(event) {
  619. if ($('input[type="text"]', this.$container).is(':focus')) {
  620. return;
  621. }
  622. if (event.keyCode === 9 && this.$container.hasClass('show')) {
  623. this.$button.click();
  624. }
  625. else {
  626. var $items = $(this.$container).find(".dropdown-item:not(.disabled)").filter(":visible");
  627. if (!$items.length) {
  628. return;
  629. }
  630. var index = $items.index($items.filter(':focus'));
  631. // Navigation up.
  632. if (event.keyCode === 38 && index > 0) {
  633. index--;
  634. }
  635. // Navigate down.
  636. else if (event.keyCode === 40 && index < $items.length - 1) {
  637. index++;
  638. }
  639. else if (!~index) {
  640. index = 0;
  641. }
  642. var $current = $items.eq(index);
  643. $current.focus();
  644. if (event.keyCode === 32 || event.keyCode === 13) {
  645. var $checkbox = $current.find('input');
  646. $checkbox.prop("checked", !$checkbox.prop("checked"));
  647. $checkbox.change();
  648. }
  649. event.stopPropagation();
  650. event.preventDefault();
  651. }
  652. }, this));
  653. if (this.options.enableClickableOptGroups && this.options.multiple) {
  654. $(".multiselect-group input", this.$ul).on("change", $.proxy(function(event) {
  655. event.stopPropagation();
  656. var $target = $(event.target);
  657. var checked = $target.prop('checked') || false;
  658. var $li = $(event.target).closest('.multiselect-item');
  659. var $group = $li.nextUntil(".multiselect-group")
  660. .not('.multiselect-filter-hidden')
  661. .not('.disabled');
  662. var $inputs = $group.find("input");
  663. var values = [];
  664. var $options = [];
  665. if (this.options.selectedClass) {
  666. if (checked) {
  667. $li.addClass(this.options.selectedClass);
  668. }
  669. else {
  670. $li.removeClass(this.options.selectedClass);
  671. }
  672. }
  673. $.each($inputs, $.proxy(function(index, input) {
  674. var value = $(input).val();
  675. var $option = this.getOptionByValue(value);
  676. if (checked) {
  677. $(input).prop('checked', true);
  678. $(input).closest('.multiselect-item')
  679. .addClass(this.options.selectedClass);
  680. $option.prop('selected', true);
  681. }
  682. else {
  683. $(input).prop('checked', false);
  684. $(input).closest('.multiselect-item')
  685. .removeClass(this.options.selectedClass);
  686. $option.prop('selected', false);
  687. }
  688. $options.push(this.getOptionByValue(value));
  689. }, this))
  690. // Cannot use select or deselect here because it would call updateOptGroups again.
  691. this.options.onChange($options, checked);
  692. this.updateButtonText();
  693. this.updateSelectAll();
  694. }, this));
  695. }
  696. if (this.options.enableCollapsibleOptGroups && this.options.multiple) {
  697. $(".multiselect-group .caret-container", this.$ul).on("click", $.proxy(function(event) {
  698. var $li = $(event.target).closest('.multiselect-item');
  699. var $inputs = $li.nextUntil(".multiselect-group")
  700. .not('.multiselect-filter-hidden');
  701. var visible = true;
  702. $inputs.each(function() {
  703. visible = visible && $(this).is(':visible');
  704. });
  705. if (visible) {
  706. $inputs.hide()
  707. .addClass('multiselect-collapsible-hidden');
  708. }
  709. else {
  710. $inputs.show()
  711. .removeClass('multiselect-collapsible-hidden');
  712. }
  713. }, this));
  714. $(".multiselect-all", this.$ul).css('background', '#f3f3f3').css('border-bottom', '1px solid #eaeaea');
  715. $(".multiselect-all > label.form-check-label", this.$ul).css('padding', '3px 20px 3px 35px');
  716. $(".multiselect-group > input", this.$ul).css('margin', '4px 0px 5px -20px');
  717. }
  718. },
  719. /**
  720. * Create an option using the given select option.
  721. *
  722. * @param {jQuery} element
  723. */
  724. createOptionValue: function(element) {
  725. var $element = $(element);
  726. if ($element.is(':selected')) {
  727. $element.prop('selected', true);
  728. }
  729. // Support the label attribute on options.
  730. var label = this.options.optionLabel(element);
  731. var classes = this.options.optionClass(element);
  732. var value = $element.val();
  733. var inputType = this.options.multiple ? "checkbox" : "radio";
  734. var $li = $(this.options.templates.li);
  735. var $label = $('label', $li);
  736. // $label.addClass(inputType);
  737. $label.addClass('form-check-label');
  738. $li.addClass(classes);
  739. if (this.options.enableHTML) {
  740. $label.html(" " + label + "<span class='form-check-control-indicator' />");
  741. }
  742. else {
  743. $label.text(" " + label);
  744. }
  745. // $label.append('<div />');
  746. var $checkbox = $('<input/>').attr('type', inputType);
  747. var name = this.options.checkboxName($element);
  748. if (name) {
  749. $checkbox.attr('name', name);
  750. }
  751. $label.prepend($checkbox);
  752. var selected = $element.prop('selected') || false;
  753. $checkbox.val(value);
  754. if (value === this.options.selectAllValue) {
  755. $li.addClass("multiselect-item multiselect-all");
  756. // $checkbox.parent().parent()
  757. // .addClass('multiselect-all');
  758. }
  759. $label.attr('title', $element.attr('title'));
  760. this.$ul.append($li);
  761. if ($element.is(':disabled')) {
  762. $checkbox.attr('disabled', 'disabled')
  763. .prop('disabled', true)
  764. .closest('.dropdown-item')
  765. .attr("tabindex", "-1")
  766. // .closest('li')
  767. .addClass('disabled');
  768. }
  769. $checkbox.prop('checked', selected);
  770. if (selected && this.options.selectedClass) {
  771. $checkbox.closest('.dropdown-item')
  772. .addClass(this.options.selectedClass);
  773. }
  774. },
  775. /**
  776. * Creates a divider using the given select option.
  777. *
  778. * @param {jQuery} element
  779. */
  780. createDivider: function(element) {
  781. var $divider = $(this.options.templates.divider);
  782. this.$ul.append($divider);
  783. },
  784. /**
  785. * Creates an optgroup.
  786. *
  787. * @param {jQuery} group
  788. */
  789. createOptgroup: function(group) {
  790. var label = $(group).attr("label");
  791. var value = $(group).attr("value");
  792. var $li = $('<div class="multiselect-item multiselect-group form-check"><label></label></div>');
  793. var classes = this.options.optionClass(group);
  794. $li.addClass(classes);
  795. if (this.options.enableHTML) {
  796. $('label', $li).html(" " + label);
  797. }
  798. else {
  799. $('label', $li).text(" " + label);
  800. }
  801. if (this.options.enableCollapsibleOptGroups && this.options.multiple) {
  802. // $('a', $li).append('<span class="caret-container"><b class="caret"></b></span>');
  803. $($li).addClass('dropdown-toggle');
  804. }
  805. if (this.options.enableClickableOptGroups && this.options.multiple) {
  806. $('label', $li).addClass('form-check-label').prepend('<input type="checkbox" value="' + value + '"/> <span class="form-check-control-indicator" />');
  807. $li.closest('.multiselect-item').addClass('dropdown-item');
  808. }
  809. if ($(group).is(':disabled')) {
  810. $li.addClass('disabled');
  811. }
  812. this.$ul.append($li);
  813. $("option", group).each($.proxy(function($, group) {
  814. this.createOptionValue(group);
  815. }, this))
  816. },
  817. /**
  818. * Build the select all.
  819. *
  820. * Checks if a select all has already been created.
  821. */
  822. buildSelectAll: function() {
  823. if (typeof this.options.selectAllValue === 'number') {
  824. this.options.selectAllValue = this.options.selectAllValue.toString();
  825. }
  826. var alreadyHasSelectAll = this.hasSelectAll();
  827. if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple
  828. && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) {
  829. // Check whether to add a divider after the select all.
  830. if (this.options.includeSelectAllDivider) {
  831. this.$ul.prepend($(this.options.templates.divider));
  832. }
  833. var $li = $(this.options.templates.li);
  834. $('label', $li).addClass("form-check-label");
  835. if (this.options.enableHTML) {
  836. $('label', $li).html(" " + this.options.selectAllText + "<span class='form-check-control-indicator' />");
  837. }
  838. else {
  839. $('label', $li).text(" " + this.options.selectAllText);
  840. }
  841. if (this.options.selectAllName) {
  842. $('label', $li).prepend('<input type="checkbox" name="' + this.options.selectAllName + '" />');
  843. }
  844. else {
  845. $('label', $li).prepend('<input type="checkbox" />');
  846. }
  847. var $checkbox = $('input', $li);
  848. $checkbox.val(this.options.selectAllValue);
  849. $li.addClass("multiselect-item multiselect-all");
  850. // $checkbox.parent().parent()
  851. // .addClass('multiselect-all');
  852. this.$ul.prepend($li);
  853. $checkbox.prop('checked', false);
  854. }
  855. },
  856. /**
  857. * Builds the filter.
  858. */
  859. buildFilter: function() {
  860. // Build filter if filtering OR case insensitive filtering is enabled and the number of options exceeds (or equals) enableFilterLength.
  861. if (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering) {
  862. var enableFilterLength = Math.max(this.options.enableFiltering, this.options.enableCaseInsensitiveFiltering);
  863. if (this.$select.find('option').length >= enableFilterLength) {
  864. this.$filter = $(this.options.templates.filter);
  865. $('input', this.$filter).attr('placeholder', this.options.filterPlaceholder);
  866. // Adds optional filter clear button
  867. if(this.options.includeFilterClearBtn) {
  868. var clearBtn = $(this.options.templates.filterClearBtn);
  869. clearBtn.on('click', $.proxy(function(event){
  870. clearTimeout(this.searchTimeout);
  871. this.$filter.find('.multiselect-search').val('');
  872. $('.multiselect-item', this.$ul).show().removeClass('multiselect-filter-hidden');
  873. this.updateSelectAll();
  874. if (this.options.enableClickableOptGroups && this.options.multiple) {
  875. this.updateOptGroups();
  876. }
  877. }, this));
  878. this.$filter.find('.input-group').append(clearBtn);
  879. }
  880. this.$ul.prepend(this.$filter);
  881. this.$filter.val(this.query).on('click', function(event) {
  882. event.stopPropagation();
  883. }).on('input keydown', $.proxy(function(event) {
  884. // Cancel enter key default behaviour
  885. if (event.which === 13) {
  886. event.preventDefault();
  887. }
  888. // This is useful to catch "keydown" events after the browser has updated the control.
  889. clearTimeout(this.searchTimeout);
  890. this.searchTimeout = this.asyncFunction($.proxy(function() {
  891. if (this.query !== event.target.value) {
  892. this.query = event.target.value;
  893. var currentGroup, currentGroupVisible;
  894. $.each($('.multiselect-item', this.$ul), $.proxy(function(index, element) {
  895. var value = $('input', element).length > 0 ? $('input', element).val() : "";
  896. var text = $('label', element).text();
  897. var filterCandidate = '';
  898. if ((this.options.filterBehavior === 'text')) {
  899. filterCandidate = text;
  900. }
  901. else if ((this.options.filterBehavior === 'value')) {
  902. filterCandidate = value;
  903. }
  904. else if (this.options.filterBehavior === 'both') {
  905. filterCandidate = text + '\n' + value;
  906. }
  907. if (value !== this.options.selectAllValue && text) {
  908. // By default lets assume that element is not
  909. // interesting for this search.
  910. var showElement = false;
  911. if (this.options.enableCaseInsensitiveFiltering) {
  912. filterCandidate = filterCandidate.toLowerCase();
  913. this.query = this.query.toLowerCase();
  914. }
  915. if (this.options.enableFullValueFiltering && this.options.filterBehavior !== 'both') {
  916. var valueToMatch = filterCandidate.trim().substring(0, this.query.length);
  917. if (this.query.indexOf(valueToMatch) > -1) {
  918. showElement = true;
  919. }
  920. }
  921. else if (filterCandidate.indexOf(this.query) > -1) {
  922. showElement = true;
  923. }
  924. // Toggle current element (group or group item) according to showElement boolean.
  925. $(element).toggle(showElement)
  926. .toggleClass('multiselect-filter-hidden', !showElement);
  927. // Differentiate groups and group items.
  928. if ($(element).hasClass('multiselect-group')) {
  929. // Remember group status.
  930. currentGroup = element;
  931. currentGroupVisible = showElement;
  932. }
  933. else {
  934. // Show group name when at least one of its items is visible.
  935. if (showElement) {
  936. $(currentGroup).show()
  937. .removeClass('multiselect-filter-hidden');
  938. }
  939. // Show all group items when group name satisfies filter.
  940. if (!showElement && currentGroupVisible) {
  941. $(element).show()
  942. .removeClass('multiselect-filter-hidden');
  943. }
  944. }
  945. }
  946. }, this));
  947. }
  948. this.updateSelectAll();
  949. if (this.options.enableClickableOptGroups && this.options.multiple) {
  950. this.updateOptGroups();
  951. }
  952. this.options.onFiltering(event.target);
  953. }, this), 300, this);
  954. }, this));
  955. }
  956. }
  957. },
  958. /**
  959. * Unbinds the whole plugin.
  960. */
  961. destroy: function() {
  962. this.$container.remove();
  963. this.$select.unwrap();
  964. // reset original state
  965. this.$select.prop('disabled', this.options.wasDisabled);
  966. this.$select.data('multiselect', null);
  967. },
  968. /**
  969. * Refreshs the multiselect based on the selected options of the select.
  970. */
  971. refresh: function () {
  972. var inputs = $.map($('.multiselect-item input', this.$ul), $);
  973. $('option', this.$select).each($.proxy(function (index, element) {
  974. var $elem = $(element);
  975. var value = $elem.val();
  976. var $input;
  977. for (var i = inputs.length; 0 < i--; /**/) {
  978. if (value !== ($input = inputs[i]).val())
  979. continue; // wrong li
  980. if ($elem.is(':selected')) {
  981. $input.prop('checked', true);
  982. if (this.options.selectedClass) {
  983. $input.closest('.multiselect-item')
  984. .addClass(this.options.selectedClass);
  985. }
  986. }
  987. else {
  988. $input.prop('checked', false);
  989. if (this.options.selectedClass) {
  990. $input.closest('.multiselect-item')
  991. .removeClass(this.options.selectedClass);
  992. }
  993. }
  994. if ($elem.is(":disabled")) {
  995. $input.attr('disabled', 'disabled')
  996. .prop('disabled', true)
  997. .closest('.multiselect-item')
  998. .addClass('disabled');
  999. }
  1000. else {
  1001. $input.prop('disabled', false)
  1002. .closest('.multiselect-item')
  1003. .removeClass('disabled');
  1004. }
  1005. break; // assumes unique values
  1006. }
  1007. }, this));
  1008. this.updateButtonText();
  1009. this.updateSelectAll();
  1010. if (this.options.enableClickableOptGroups && this.options.multiple) {
  1011. this.updateOptGroups();
  1012. }
  1013. },
  1014. /**
  1015. * Select all options of the given values.
  1016. *
  1017. * If triggerOnChange is set to true, the on change event is triggered if
  1018. * and only if one value is passed.
  1019. *
  1020. * @param {Array} selectValues
  1021. * @param {Boolean} triggerOnChange
  1022. */
  1023. select: function(selectValues, triggerOnChange) {
  1024. if(!$.isArray(selectValues)) {
  1025. selectValues = [selectValues];
  1026. }
  1027. for (var i = 0; i < selectValues.length; i++) {
  1028. var value = selectValues[i];
  1029. if (value === null || value === undefined) {
  1030. continue;
  1031. }
  1032. var $option = this.getOptionByValue(value);
  1033. var $checkbox = this.getInputByValue(value);
  1034. if($option === undefined || $checkbox === undefined) {
  1035. continue;
  1036. }
  1037. if (!this.options.multiple) {
  1038. this.deselectAll(false);
  1039. }
  1040. if (this.options.selectedClass) {
  1041. $checkbox.closest('.multiselect-item')
  1042. .addClass(this.options.selectedClass);
  1043. }
  1044. $checkbox.prop('checked', true);
  1045. $option.prop('selected', true);
  1046. if (triggerOnChange) {
  1047. this.options.onChange($option, true);
  1048. }
  1049. }
  1050. this.updateButtonText();
  1051. this.updateSelectAll();
  1052. if (this.options.enableClickableOptGroups && this.options.multiple) {
  1053. this.updateOptGroups();
  1054. }
  1055. },
  1056. /**
  1057. * Clears all selected items.
  1058. */
  1059. clearSelection: function () {
  1060. this.deselectAll(false);
  1061. this.updateButtonText();
  1062. this.updateSelectAll();
  1063. if (this.options.enableClickableOptGroups && this.options.multiple) {
  1064. this.updateOptGroups();
  1065. }
  1066. },
  1067. /**
  1068. * Deselects all options of the given values.
  1069. *
  1070. * If triggerOnChange is set to true, the on change event is triggered, if
  1071. * and only if one value is passed.
  1072. *
  1073. * @param {Array} deselectValues
  1074. * @param {Boolean} triggerOnChange
  1075. */
  1076. deselect: function(deselectValues, triggerOnChange) {
  1077. if(!$.isArray(deselectValues)) {
  1078. deselectValues = [deselectValues];
  1079. }
  1080. for (var i = 0; i < deselectValues.length; i++) {
  1081. var value = deselectValues[i];
  1082. if (value === null || value === undefined) {
  1083. continue;
  1084. }
  1085. var $option = this.getOptionByValue(value);
  1086. var $checkbox = this.getInputByValue(value);
  1087. if($option === undefined || $checkbox === undefined) {
  1088. continue;
  1089. }
  1090. if (this.options.selectedClass) {
  1091. $checkbox.closest('.multiselect-item')
  1092. .removeClass(this.options.selectedClass);
  1093. }
  1094. $checkbox.prop('checked', false);
  1095. $option.prop('selected', false);
  1096. if (triggerOnChange) {
  1097. this.options.onChange($option, false);
  1098. }
  1099. }
  1100. this.updateButtonText();
  1101. this.updateSelectAll();
  1102. if (this.options.enableClickableOptGroups && this.options.multiple) {
  1103. this.updateOptGroups();
  1104. }
  1105. },
  1106. /**
  1107. * Selects all enabled & visible options.
  1108. *
  1109. * If justVisible is true or not specified, only visible options are selected.
  1110. *
  1111. * @param {Boolean} justVisible
  1112. * @param {Boolean} triggerOnSelectAll
  1113. */
  1114. selectAll: function (justVisible, triggerOnSelectAll) {
  1115. var justVisible = typeof justVisible === 'undefined' ? true : justVisible;
  1116. var allLis = $(".multiselect-item:not(.dropdown-divider):not(.disabled):not(.multiselect-group)", this.$ul);
  1117. var visibleLis = $(".multiselect-item:not(.dropdown-divider):not(.disabled):not(.multiselect-group):not(.multiselect-filter-hidden):not(.multiselect-collapisble-hidden)", this.$ul).filter(':visible');
  1118. if(justVisible) {
  1119. $('input:enabled' , visibleLis).prop('checked', true);
  1120. visibleLis.addClass(this.options.selectedClass);
  1121. $('input:enabled' , visibleLis).each($.proxy(function(index, element) {
  1122. var value = $(element).val();
  1123. var option = this.getOptionByValue(value);
  1124. $(option).prop('selected', true);
  1125. }, this));
  1126. }
  1127. else {
  1128. $('input:enabled' , allLis).prop('checked', true);
  1129. allLis.addClass(this.options.selectedClass);
  1130. $('input:enabled' , allLis).each($.proxy(function(index, element) {
  1131. var value = $(element).val();
  1132. var option = this.getOptionByValue(value);
  1133. $(option).prop('selected', true);
  1134. }, this));
  1135. }
  1136. $('.multiselect-item input[value="' + this.options.selectAllValue + '"]', this.$ul).prop('checked', true);
  1137. if (this.options.enableClickableOptGroups && this.options.multiple) {
  1138. this.updateOptGroups();
  1139. }
  1140. if (triggerOnSelectAll) {
  1141. this.options.onSelectAll();
  1142. }
  1143. },
  1144. /**
  1145. * Deselects all options.
  1146. *
  1147. * If justVisible is true or not specified, only visible options are deselected.
  1148. *
  1149. * @param {Boolean} justVisible
  1150. */
  1151. deselectAll: function (justVisible, triggerOnDeselectAll) {
  1152. var justVisible = typeof justVisible === 'undefined' ? true : justVisible;
  1153. var allLis = $(".multiselect-item:not(.dropdown-divider):not(.disabled):not(.multiselect-group)", this.$ul);
  1154. var visibleLis = $(".multiselect-item:not(.dropdown-divider):not(.disabled):not(.multiselect-group):not(.multiselect-filter-hidden):not(.multiselect-collapisble-hidden)", this.$ul).filter(':visible');
  1155. if(justVisible) {
  1156. $('input[type="checkbox"]:enabled' , visibleLis).prop('checked', false);
  1157. visibleLis.removeClass(this.options.selectedClass);
  1158. $('input[type="checkbox"]:enabled' , visibleLis).each($.proxy(function(index, element) {
  1159. var value = $(element).val();
  1160. var option = this.getOptionByValue(value);
  1161. $(option).prop('selected', false);
  1162. }, this));
  1163. }
  1164. else {
  1165. $('input[type="checkbox"]:enabled' , allLis).prop('checked', false);
  1166. allLis.removeClass(this.options.selectedClass);
  1167. $('input[type="checkbox"]:enabled' , allLis).each($.proxy(function(index, element) {
  1168. var value = $(element).val();
  1169. var option = this.getOptionByValue(value);
  1170. $(option).prop('selected', false);
  1171. }, this));
  1172. }
  1173. $('.multiselect-item input[value="' + this.options.selectAllValue + '"]', this.$ul).prop('checked', false);
  1174. if (this.options.enableClickableOptGroups && this.options.multiple) {
  1175. this.updateOptGroups();
  1176. }
  1177. if (triggerOnDeselectAll) {
  1178. this.options.onDeselectAll();
  1179. }
  1180. },
  1181. /**
  1182. * Rebuild the plugin.
  1183. *
  1184. * Rebuilds the dropdown, the filter and the select all option.
  1185. */
  1186. rebuild: function() {
  1187. this.$ul.html('');
  1188. // Important to distinguish between radios and checkboxes.
  1189. this.options.multiple = this.$select.attr('multiple') === "multiple";
  1190. this.buildSelectAll();
  1191. this.buildDropdownOptions();
  1192. this.buildFilter();
  1193. this.updateButtonText();
  1194. this.updateSelectAll(true);
  1195. if (this.options.enableClickableOptGroups && this.options.multiple) {
  1196. this.updateOptGroups();
  1197. }
  1198. if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) {
  1199. this.disable();
  1200. }
  1201. else {
  1202. this.enable();
  1203. }
  1204. if (this.options.dropRight) {
  1205. this.$ul.addClass('dropdown-menu-right');
  1206. }
  1207. },
  1208. /**
  1209. * The provided data will be used to build the dropdown.
  1210. */
  1211. dataprovider: function(dataprovider) {
  1212. var groupCounter = 0;
  1213. var $select = this.$select.empty();
  1214. $.each(dataprovider, function (index, option) {
  1215. var $tag;
  1216. if ($.isArray(option.children)) { // create optiongroup tag
  1217. groupCounter++;
  1218. $tag = $('<optgroup/>').attr({
  1219. label: option.label || 'Group ' + groupCounter,
  1220. disabled: !!option.disabled
  1221. });
  1222. forEach(option.children, function(subOption) { // add children option tags
  1223. var attributes = {
  1224. value: subOption.value,
  1225. label: subOption.label || subOption.value,
  1226. title: subOption.title,
  1227. selected: !!subOption.selected,
  1228. disabled: !!subOption.disabled
  1229. };
  1230. //Loop through attributes object and add key-value for each attribute
  1231. for (var key in subOption.attributes) {
  1232. attributes['data-' + key] = subOption.attributes[key];
  1233. }
  1234. //Append original attributes + new data attributes to option
  1235. $tag.append($('<option/>').attr(attributes));
  1236. });
  1237. }
  1238. else {
  1239. var attributes = {
  1240. 'value': option.value,
  1241. 'label': option.label || option.value,
  1242. 'title': option.title,
  1243. 'class': option.class,
  1244. 'selected': !!option.selected,
  1245. 'disabled': !!option.disabled
  1246. };
  1247. //Loop through attributes object and add key-value for each attribute
  1248. for (var key in option.attributes) {
  1249. attributes['data-' + key] = option.attributes[key];
  1250. }
  1251. //Append original attributes + new data attributes to option
  1252. $tag = $('<option/>').attr(attributes);
  1253. $tag.text(option.label || option.value);
  1254. }
  1255. $select.append($tag);
  1256. });
  1257. this.rebuild();
  1258. },
  1259. /**
  1260. * Enable the multiselect.
  1261. */
  1262. enable: function() {
  1263. this.$select.prop('disabled', false);
  1264. this.$button.prop('disabled', false)
  1265. .removeClass('disabled');
  1266. },
  1267. /**
  1268. * Disable the multiselect.
  1269. */
  1270. disable: function() {
  1271. this.$select.prop('disabled', true);
  1272. this.$button.prop('disabled', true)
  1273. .addClass('disabled');
  1274. },
  1275. /**
  1276. * Set the options.
  1277. *
  1278. * @param {Array} options
  1279. */
  1280. setOptions: function(options) {
  1281. this.options = this.mergeOptions(options);
  1282. },
  1283. /**
  1284. * Merges the given options with the default options.
  1285. *
  1286. * @param {Array} options
  1287. * @returns {Array}
  1288. */
  1289. mergeOptions: function(options) {
  1290. return $.extend(true, {}, this.defaults, this.options, options);
  1291. },
  1292. /**
  1293. * Checks whether a select all checkbox is present.
  1294. *
  1295. * @returns {Boolean}
  1296. */
  1297. hasSelectAll: function() {
  1298. return $('a.multiselect-all', this.$ul).length > 0;
  1299. },
  1300. /**
  1301. * Update opt groups.
  1302. */
  1303. updateOptGroups: function() {
  1304. var $groups = $('.multiselect-group', this.$ul)
  1305. var selectedClass = this.options.selectedClass;
  1306. $groups.each(function() {
  1307. var $options = $(this).nextUntil('.multiselect-group')
  1308. .not('.multiselect-filter-hidden')
  1309. .not('.disabled');
  1310. var checked = true;
  1311. $options.each(function() {
  1312. var $input = $('input', this);
  1313. if (!$input.prop('checked')) {
  1314. checked = false;
  1315. }
  1316. });
  1317. if (selectedClass) {
  1318. if (checked) {
  1319. $(this).addClass(selectedClass);
  1320. }
  1321. else {
  1322. $(this).removeClass(selectedClass);
  1323. }
  1324. }
  1325. $('input', this).prop('checked', checked);
  1326. });
  1327. },
  1328. /**
  1329. * Updates the select all checkbox based on the currently displayed and selected checkboxes.
  1330. */
  1331. updateSelectAll: function(notTriggerOnSelectAll) {
  1332. if (this.hasSelectAll()) {
  1333. // var allBoxes = $(":not(.multiselect-item):not(.multiselect-filter-hidden):not(.multiselect-group):not(.disabled) input:enabled", this.$ul);
  1334. var allBoxes = $(".dropdown-item:not(.multiselect-group):not(.multiselect-all):not(.disabled) input:enabled", this.$ul);
  1335. var allBoxesLength = allBoxes.length;
  1336. var checkedBoxesLength = allBoxes.filter(":checked").length;
  1337. var selectAllLi = $("a.multiselect-all", this.$ul);
  1338. var selectAllInput = selectAllLi.find("input");
  1339. if (checkedBoxesLength > 0 && checkedBoxesLength === allBoxesLength) {
  1340. selectAllInput.prop("checked", true);
  1341. selectAllLi.addClass(this.options.selectedClass).addClass('asflkjnsdflkjbsdhqf');
  1342. }
  1343. else {
  1344. selectAllInput.prop("checked", false);
  1345. selectAllLi.removeClass(this.options.selectedClass);
  1346. }
  1347. }
  1348. },
  1349. /**
  1350. * Update the button text and its title based on the currently selected options.
  1351. */
  1352. updateButtonText: function() {
  1353. var options = this.getSelected();
  1354. // First update the displayed button text.
  1355. if (this.options.enableHTML) {
  1356. $('.multiselect .multiselect-selected-text', this.$container).html(this.options.buttonText(options, this.$select));
  1357. }
  1358. else {
  1359. $('.multiselect .multiselect-selected-text', this.$container).text(this.options.buttonText(options, this.$select));
  1360. }
  1361. // Now update the title attribute of the button.
  1362. $('.multiselect', this.$container).attr('title', this.options.buttonTitle(options, this.$select));
  1363. },
  1364. /**
  1365. * Get all selected options.
  1366. *
  1367. * @returns {jQUery}
  1368. */
  1369. getSelected: function() {
  1370. return $('option', this.$select).filter(":selected");
  1371. },
  1372. /**
  1373. * Gets a select option by its value.
  1374. *
  1375. * @param {String} value
  1376. * @returns {jQuery}
  1377. */
  1378. getOptionByValue: function (value) {
  1379. var options = $('option', this.$select);
  1380. var valueToCompare = value.toString();
  1381. for (var i = 0; i < options.length; i = i + 1) {
  1382. var option = options[i];
  1383. if (option.value === valueToCompare) {
  1384. return $(option);
  1385. }
  1386. }
  1387. },
  1388. /**
  1389. * Get the input (radio/checkbox) by its value.
  1390. *
  1391. * @param {String} value
  1392. * @returns {jQuery}
  1393. */
  1394. getInputByValue: function (value) {
  1395. var checkboxes = $('.multiselect-item input:not(.multiselect-search)', this.$ul);
  1396. var valueToCompare = value.toString();
  1397. for (var i = 0; i < checkboxes.length; i = i + 1) {
  1398. var checkbox = checkboxes[i];
  1399. if (checkbox.value === valueToCompare) {
  1400. return $(checkbox);
  1401. }
  1402. }
  1403. },
  1404. /**
  1405. * Used for knockout integration.
  1406. */
  1407. updateOriginalOptions: function() {
  1408. this.originalOptions = this.$select.clone()[0].options;
  1409. },
  1410. asyncFunction: function(callback, timeout, self) {
  1411. var args = Array.prototype.slice.call(arguments, 3);
  1412. return setTimeout(function() {
  1413. callback.apply(self || window, args);
  1414. }, timeout);
  1415. },
  1416. setAllSelectedText: function(allSelectedText) {
  1417. this.options.allSelectedText = allSelectedText;
  1418. this.updateButtonText();
  1419. }
  1420. };
  1421. $.fn.multiselect = function(option, parameter, extraOptions) {
  1422. return this.each(function() {
  1423. var data = $(this).data('multiselect');
  1424. var options = typeof option === 'object' && option;
  1425. // Initialize the multiselect.
  1426. if (!data) {
  1427. data = new Multiselect(this, options);
  1428. $(this).data('multiselect', data);
  1429. }
  1430. // Call multiselect method.
  1431. if (typeof option === 'string') {
  1432. data[option](parameter, extraOptions);
  1433. if (option === 'destroy') {
  1434. $(this).data('multiselect', false);
  1435. }
  1436. }
  1437. });
  1438. };
  1439. $.fn.multiselect.Constructor = Multiselect;
  1440. $(function() {
  1441. $("select[data-role=multiselect]").multiselect();
  1442. });
  1443. }(window.jQuery);