bootstrap-multiselect.js 67 KB

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