You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

jquery.multiselect.js 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. /* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, boss:true, undef:true, curly:true, browser:true, jquery:true */
  2. /*
  3. * jQuery MultiSelect UI Widget 1.14pre
  4. * Copyright (c) 2012 Eric Hynds
  5. *
  6. * http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/
  7. *
  8. * Depends:
  9. * - jQuery 1.4.2+
  10. * - jQuery UI 1.8 widget factory
  11. *
  12. * Optional:
  13. * - jQuery UI effects
  14. * - jQuery UI position utility
  15. *
  16. * Dual licensed under the MIT and GPL licenses:
  17. * http://www.opensource.org/licenses/mit-license.php
  18. * http://www.gnu.org/licenses/gpl.html
  19. *
  20. */
  21. (function($, undefined) {
  22. var multiselectID = 0;
  23. var $doc = $(document);
  24. $.widget("ech.multiselect", {
  25. // default options
  26. options: {
  27. header: true,
  28. height: 175,
  29. minWidth: 225,
  30. classes: '',
  31. checkAllText: 'Check all',
  32. uncheckAllText: 'Uncheck all',
  33. noneSelectedText: 'Select options',
  34. selectedText: '# selected',
  35. selectedList: 0,
  36. show: null,
  37. hide: null,
  38. autoOpen: false,
  39. multiple: true,
  40. position: {}
  41. },
  42. _create: function() {
  43. var el = this.element.hide();
  44. var o = this.options;
  45. this.speed = $.fx.speeds._default; // default speed for effects
  46. this._isOpen = false; // assume no
  47. // create a unique namespace for events that the widget
  48. // factory cannot unbind automatically. Use eventNamespace if on
  49. // jQuery UI 1.9+, and otherwise fallback to a custom string.
  50. this._namespaceID = this.eventNamespace || ('multiselect' + multiselectID);
  51. var button = (this.button = $('<button type="button"><span class="ui-icon ui-icon-triangle-2-n-s"></span></button>'))
  52. .addClass('ui-multiselect ui-widget ui-state-default ui-corner-all')
  53. .addClass(o.classes)
  54. .attr({ 'title':el.attr('title'), 'aria-haspopup':true, 'tabIndex':el.attr('tabIndex') })
  55. .insertAfter(el),
  56. buttonlabel = (this.buttonlabel = $('<span />'))
  57. .html(o.noneSelectedText)
  58. .appendTo(button),
  59. menu = (this.menu = $('<div />'))
  60. .addClass('ui-multiselect-menu ui-widget ui-widget-content ui-corner-all')
  61. .addClass(o.classes)
  62. .appendTo(document.body),
  63. header = (this.header = $('<div />'))
  64. .addClass('ui-widget-header ui-corner-all ui-multiselect-header ui-helper-clearfix')
  65. .appendTo(menu),
  66. headerLinkContainer = (this.headerLinkContainer = $('<ul />'))
  67. .addClass('ui-helper-reset')
  68. .html(function() {
  69. if(o.header === true) {
  70. return '<li><a class="ui-multiselect-all" href="#"><span class="ui-icon ui-icon-check"></span><span>' + o.checkAllText + '</span></a></li><li><a class="ui-multiselect-none" href="#"><span class="ui-icon ui-icon-closethick"></span><span>' + o.uncheckAllText + '</span></a></li>';
  71. } else if(typeof o.header === "string") {
  72. return '<li>' + o.header + '</li>';
  73. } else {
  74. return '';
  75. }
  76. })
  77. .append('<li class="ui-multiselect-close"><a href="#" class="ui-multiselect-close"><span class="ui-icon ui-icon-circle-close"></span></a></li>')
  78. .appendTo(header),
  79. checkboxContainer = (this.checkboxContainer = $('<ul />'))
  80. .addClass('ui-multiselect-checkboxes ui-helper-reset')
  81. .appendTo(menu);
  82. // perform event bindings
  83. this._bindEvents();
  84. // build menu
  85. this.refresh(true);
  86. // some addl. logic for single selects
  87. if(!o.multiple) {
  88. menu.addClass('ui-multiselect-single');
  89. }
  90. // bump unique ID
  91. multiselectID++;
  92. },
  93. _init: function() {
  94. if(this.options.header === false) {
  95. this.header.hide();
  96. }
  97. if(!this.options.multiple) {
  98. this.headerLinkContainer.find('.ui-multiselect-all, .ui-multiselect-none').hide();
  99. }
  100. if(this.options.autoOpen) {
  101. this.open();
  102. }
  103. if(this.element.is(':disabled')) {
  104. this.disable();
  105. }
  106. },
  107. refresh: function(init) {
  108. var el = this.element;
  109. var o = this.options;
  110. var menu = this.menu;
  111. var checkboxContainer = this.checkboxContainer;
  112. var optgroups = [];
  113. var html = "";
  114. var id = el.attr('id') || multiselectID++; // unique ID for the label & option tags
  115. // build items
  116. el.find('option').each(function(i) {
  117. var $this = $(this);
  118. var parent = this.parentNode;
  119. var title = this.innerHTML;
  120. var description = this.title;
  121. var value = this.value;
  122. var inputID = 'ui-multiselect-' + (this.id || id + '-option-' + i);
  123. var isDisabled = this.disabled;
  124. var isSelected = this.selected;
  125. var labelClasses = [ 'ui-corner-all' ];
  126. var liClasses = (isDisabled ? 'ui-multiselect-disabled ' : ' ') + this.className;
  127. var optLabel;
  128. // is this an optgroup?
  129. if(parent.tagName === 'OPTGROUP') {
  130. optLabel = parent.getAttribute('label');
  131. // has this optgroup been added already?
  132. if($.inArray(optLabel, optgroups) === -1) {
  133. html += '<li class="ui-multiselect-optgroup-label ' + parent.className + '"><a href="#">' + optLabel + '</a></li>';
  134. optgroups.push(optLabel);
  135. }
  136. }
  137. if(isDisabled) {
  138. labelClasses.push('ui-state-disabled');
  139. }
  140. // browsers automatically select the first option
  141. // by default with single selects
  142. if(isSelected && !o.multiple) {
  143. labelClasses.push('ui-state-active');
  144. }
  145. html += '<li class="' + liClasses + '">';
  146. // create the label
  147. html += '<label for="' + inputID + '" title="' + description + '" class="' + labelClasses.join(' ') + '">';
  148. html += '<input id="' + inputID + '" name="multiselect_' + id + '" type="' + (o.multiple ? "checkbox" : "radio") + '" value="' + value + '" title="' + title + '"';
  149. // pre-selected?
  150. if(isSelected) {
  151. html += ' checked="checked"';
  152. html += ' aria-selected="true"';
  153. }
  154. // disabled?
  155. if(isDisabled) {
  156. html += ' disabled="disabled"';
  157. html += ' aria-disabled="true"';
  158. }
  159. // add the title and close everything off
  160. html += ' /><span>' + title + '</span></label></li>';
  161. });
  162. // insert into the DOM
  163. checkboxContainer.html(html);
  164. // cache some moar useful elements
  165. this.labels = menu.find('label');
  166. this.inputs = this.labels.children('input');
  167. // set widths
  168. this._setButtonWidth();
  169. this._setMenuWidth();
  170. // remember default value
  171. this.button[0].defaultValue = this.update();
  172. // broadcast refresh event; useful for widgets
  173. if(!init) {
  174. this._trigger('refresh');
  175. }
  176. },
  177. // updates the button text. call refresh() to rebuild
  178. update: function() {
  179. var o = this.options;
  180. var $inputs = this.inputs;
  181. var $checked = $inputs.filter(':checked');
  182. var numChecked = $checked.length;
  183. var value;
  184. if(numChecked === 0) {
  185. value = o.noneSelectedText;
  186. } else {
  187. if($.isFunction(o.selectedText)) {
  188. value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get());
  189. } else if(/\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList) {
  190. value = $checked.map(function() { return $(this).next().html(); }).get().join(', ');
  191. } else {
  192. value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length);
  193. }
  194. }
  195. this._setButtonValue(value);
  196. return value;
  197. },
  198. // this exists as a separate method so that the developer
  199. // can easily override it.
  200. _setButtonValue: function(value) {
  201. this.buttonlabel.text(value);
  202. },
  203. // binds events
  204. _bindEvents: function() {
  205. var self = this;
  206. var button = this.button;
  207. function clickHandler() {
  208. self[ self._isOpen ? 'close' : 'open' ]();
  209. return false;
  210. }
  211. // webkit doesn't like it when you click on the span :(
  212. button
  213. .find('span')
  214. .bind('click.multiselect', clickHandler);
  215. // button events
  216. button.bind({
  217. click: clickHandler,
  218. keypress: function(e) {
  219. switch(e.which) {
  220. case 27: // esc
  221. case 38: // up
  222. case 37: // left
  223. self.close();
  224. break;
  225. case 39: // right
  226. case 40: // down
  227. self.open();
  228. break;
  229. }
  230. },
  231. mouseenter: function() {
  232. if(!button.hasClass('ui-state-disabled')) {
  233. $(this).addClass('ui-state-hover');
  234. }
  235. },
  236. mouseleave: function() {
  237. $(this).removeClass('ui-state-hover');
  238. },
  239. focus: function() {
  240. if(!button.hasClass('ui-state-disabled')) {
  241. $(this).addClass('ui-state-focus');
  242. }
  243. },
  244. blur: function() {
  245. $(this).removeClass('ui-state-focus');
  246. }
  247. });
  248. // header links
  249. this.header.delegate('a', 'click.multiselect', function(e) {
  250. // close link
  251. if($(this).hasClass('ui-multiselect-close')) {
  252. self.close();
  253. // check all / uncheck all
  254. } else {
  255. self[$(this).hasClass('ui-multiselect-all') ? 'checkAll' : 'uncheckAll']();
  256. }
  257. e.preventDefault();
  258. });
  259. // optgroup label toggle support
  260. this.menu.delegate('li.ui-multiselect-optgroup-label a', 'click.multiselect', function(e) {
  261. e.preventDefault();
  262. var $this = $(this);
  263. var $inputs = $this.parent().nextUntil('li.ui-multiselect-optgroup-label').find('input:visible:not(:disabled)');
  264. var nodes = $inputs.get();
  265. var label = $this.parent().text();
  266. // trigger event and bail if the return is false
  267. if(self._trigger('beforeoptgrouptoggle', e, { inputs:nodes, label:label }) === false) {
  268. return;
  269. }
  270. // toggle inputs
  271. self._toggleChecked(
  272. $inputs.filter(':checked').length !== $inputs.length,
  273. $inputs
  274. );
  275. self._trigger('optgrouptoggle', e, {
  276. inputs: nodes,
  277. label: label,
  278. checked: nodes[0].checked
  279. });
  280. })
  281. .delegate('label', 'mouseenter.multiselect', function() {
  282. if(!$(this).hasClass('ui-state-disabled')) {
  283. self.labels.removeClass('ui-state-hover');
  284. $(this).addClass('ui-state-hover').find('input').focus();
  285. }
  286. })
  287. .delegate('label', 'keydown.multiselect', function(e) {
  288. e.preventDefault();
  289. switch(e.which) {
  290. case 9: // tab
  291. case 27: // esc
  292. self.close();
  293. break;
  294. case 38: // up
  295. case 40: // down
  296. case 37: // left
  297. case 39: // right
  298. self._traverse(e.which, this);
  299. break;
  300. case 13: // enter
  301. $(this).find('input')[0].click();
  302. break;
  303. }
  304. })
  305. .delegate('input[type="checkbox"], input[type="radio"]', 'click.multiselect', function(e) {
  306. var $this = $(this);
  307. var val = this.value;
  308. var checked = this.checked;
  309. var tags = self.element.find('option');
  310. // bail if this input is disabled or the event is cancelled
  311. if(this.disabled || self._trigger('click', e, { value: val, text: this.title, checked: checked }) === false) {
  312. e.preventDefault();
  313. return;
  314. }
  315. // make sure the input has focus. otherwise, the esc key
  316. // won't close the menu after clicking an item.
  317. $this.focus();
  318. // toggle aria state
  319. $this.attr('aria-selected', checked);
  320. // change state on the original option tags
  321. tags.each(function() {
  322. if(this.value === val) {
  323. this.selected = checked;
  324. } else if(!self.options.multiple) {
  325. this.selected = false;
  326. }
  327. });
  328. // some additional single select-specific logic
  329. if(!self.options.multiple) {
  330. self.labels.removeClass('ui-state-active');
  331. $this.closest('label').toggleClass('ui-state-active', checked);
  332. // close menu
  333. self.close();
  334. }
  335. // fire change on the select box
  336. self.element.trigger("change");
  337. // setTimeout is to fix multiselect issue #14 and #47. caused by jQuery issue #3827
  338. // http://bugs.jquery.com/ticket/3827
  339. setTimeout($.proxy(self.update, self), 10);
  340. });
  341. // close each widget when clicking on any other element/anywhere else on the page
  342. $doc.bind('mousedown.' + this._namespaceID, function(e) {
  343. if(self._isOpen && !$.contains(self.menu[0], e.target) && !$.contains(self.button[0], e.target) && e.target !== self.button[0]) {
  344. self.close();
  345. }
  346. });
  347. // deal with form resets. the problem here is that buttons aren't
  348. // restored to their defaultValue prop on form reset, and the reset
  349. // handler fires before the form is actually reset. delaying it a bit
  350. // gives the form inputs time to clear.
  351. $(this.element[0].form).bind('reset.multiselect', function() {
  352. setTimeout($.proxy(self.refresh, self), 10);
  353. });
  354. },
  355. // set button width
  356. _setButtonWidth: function() {
  357. var width = this.element.outerWidth();
  358. var o = this.options;
  359. if(/\d/.test(o.minWidth) && width < o.minWidth) {
  360. width = o.minWidth;
  361. }
  362. // set widths
  363. this.button.outerWidth(width);
  364. },
  365. // set menu width
  366. _setMenuWidth: function() {
  367. var m = this.menu;
  368. m.outerWidth(this.button.outerWidth());
  369. },
  370. // move up or down within the menu
  371. _traverse: function(which, start) {
  372. var $start = $(start);
  373. var moveToLast = which === 38 || which === 37;
  374. // select the first li that isn't an optgroup label / disabled
  375. $next = $start.parent()[moveToLast ? 'prevAll' : 'nextAll']('li:not(.ui-multiselect-disabled, .ui-multiselect-optgroup-label)')[ moveToLast ? 'last' : 'first']();
  376. // if at the first/last element
  377. if(!$next.length) {
  378. var $container = this.menu.find('ul').last();
  379. // move to the first/last
  380. this.menu.find('label')[ moveToLast ? 'last' : 'first' ]().trigger('mouseover');
  381. // set scroll position
  382. $container.scrollTop(moveToLast ? $container.height() : 0);
  383. } else {
  384. $next.find('label').trigger('mouseover');
  385. }
  386. },
  387. // This is an internal function to toggle the checked property and
  388. // other related attributes of a checkbox.
  389. //
  390. // The context of this function should be a checkbox; do not proxy it.
  391. _toggleState: function(prop, flag) {
  392. return function() {
  393. if(!this.disabled) {
  394. this[ prop ] = flag;
  395. }
  396. if(flag) {
  397. this.setAttribute('aria-selected', true);
  398. } else {
  399. this.removeAttribute('aria-selected');
  400. }
  401. };
  402. },
  403. _toggleChecked: function(flag, group) {
  404. var $inputs = (group && group.length) ? group : this.inputs;
  405. var self = this;
  406. // toggle state on inputs
  407. $inputs.each(this._toggleState('checked', flag));
  408. // give the first input focus
  409. $inputs.eq(0).focus();
  410. // update button text
  411. this.update();
  412. // gather an array of the values that actually changed
  413. var values = $inputs.map(function() {
  414. return this.value;
  415. }).get();
  416. // toggle state on original option tags
  417. this.element
  418. .find('option')
  419. .each(function() {
  420. if(!this.disabled && $.inArray(this.value, values) > -1) {
  421. self._toggleState('selected', flag).call(this);
  422. }
  423. });
  424. // trigger the change event on the select
  425. if($inputs.length) {
  426. this.element.trigger("change");
  427. }
  428. },
  429. _toggleDisabled: function(flag) {
  430. this.button.attr({ 'disabled':flag, 'aria-disabled':flag })[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled');
  431. var inputs = this.menu.find('input');
  432. var key = "ech-multiselect-disabled";
  433. if(flag) {
  434. // remember which elements this widget disabled (not pre-disabled)
  435. // elements, so that they can be restored if the widget is re-enabled.
  436. inputs = inputs.filter(':enabled').data(key, true)
  437. } else {
  438. inputs = inputs.filter(function() {
  439. return $.data(this, key) === true;
  440. }).removeData(key);
  441. }
  442. inputs
  443. .attr({ 'disabled':flag, 'arial-disabled':flag })
  444. .parent()[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled');
  445. this.element.attr({
  446. 'disabled':flag,
  447. 'aria-disabled':flag
  448. });
  449. },
  450. // open the menu
  451. open: function(e) {
  452. var self = this;
  453. var button = this.button;
  454. var menu = this.menu;
  455. var speed = this.speed;
  456. var o = this.options;
  457. var args = [];
  458. // bail if the multiselectopen event returns false, this widget is disabled, or is already open
  459. if(this._trigger('beforeopen') === false || button.hasClass('ui-state-disabled') || this._isOpen) {
  460. return;
  461. }
  462. var $container = menu.find('ul').last();
  463. var effect = o.show;
  464. // figure out opening effects/speeds
  465. if($.isArray(o.show)) {
  466. effect = o.show[0];
  467. speed = o.show[1] || self.speed;
  468. }
  469. // if there's an effect, assume jQuery UI is in use
  470. // build the arguments to pass to show()
  471. if(effect) {
  472. args = [ effect, speed ];
  473. }
  474. // set the scroll of the checkbox container
  475. $container.scrollTop(0).height(o.height);
  476. // positon
  477. this.position();
  478. // show the menu, maybe with a speed/effect combo
  479. $.fn.show.apply(menu, args);
  480. // select the first option
  481. // triggering both mouseover and mouseover because 1.4.2+ has a bug where triggering mouseover
  482. // will actually trigger mouseenter. the mouseenter trigger is there for when it's eventually fixed
  483. this.labels.eq(0).trigger('mouseover').trigger('mouseenter').find('input').trigger('focus');
  484. button.addClass('ui-state-active');
  485. this._isOpen = true;
  486. this._trigger('open');
  487. },
  488. // close the menu
  489. close: function() {
  490. if(this._trigger('beforeclose') === false) {
  491. return;
  492. }
  493. var o = this.options;
  494. var effect = o.hide;
  495. var speed = this.speed;
  496. var args = [];
  497. // figure out opening effects/speeds
  498. if($.isArray(o.hide)) {
  499. effect = o.hide[0];
  500. speed = o.hide[1] || this.speed;
  501. }
  502. if(effect) {
  503. args = [ effect, speed ];
  504. }
  505. $.fn.hide.apply(this.menu, args);
  506. this.button.removeClass('ui-state-active').trigger('blur').trigger('mouseleave');
  507. this._isOpen = false;
  508. this._trigger('close');
  509. },
  510. enable: function() {
  511. this._toggleDisabled(false);
  512. },
  513. disable: function() {
  514. this._toggleDisabled(true);
  515. },
  516. checkAll: function(e) {
  517. this._toggleChecked(true);
  518. this._trigger('checkAll');
  519. },
  520. uncheckAll: function() {
  521. this._toggleChecked(false);
  522. this._trigger('uncheckAll');
  523. },
  524. getChecked: function() {
  525. return this.menu.find('input').filter(':checked');
  526. },
  527. destroy: function() {
  528. // remove classes + data
  529. $.Widget.prototype.destroy.call(this);
  530. // unbind events
  531. $doc.unbind(this._namespaceID);
  532. this.button.remove();
  533. this.menu.remove();
  534. this.element.show();
  535. return this;
  536. },
  537. isOpen: function() {
  538. return this._isOpen;
  539. },
  540. widget: function() {
  541. return this.menu;
  542. },
  543. getButton: function() {
  544. return this.button;
  545. },
  546. position: function() {
  547. var o = this.options;
  548. // use the position utility if it exists and options are specifified
  549. if($.ui.position && !$.isEmptyObject(o.position)) {
  550. o.position.of = o.position.of || button;
  551. this.menu
  552. .show()
  553. .position(o.position)
  554. .hide();
  555. // otherwise fallback to custom positioning
  556. } else {
  557. var pos = this.button.offset();
  558. this.menu.css({
  559. top: pos.top + this.button.outerHeight(),
  560. left: pos.left
  561. });
  562. }
  563. },
  564. // react to option changes after initialization
  565. _setOption: function(key, value) {
  566. var menu = this.menu;
  567. switch(key) {
  568. case 'header':
  569. menu.find('div.ui-multiselect-header')[value ? 'show' : 'hide']();
  570. break;
  571. case 'checkAllText':
  572. menu.find('a.ui-multiselect-all span').eq(-1).text(value);
  573. break;
  574. case 'uncheckAllText':
  575. menu.find('a.ui-multiselect-none span').eq(-1).text(value);
  576. break;
  577. case 'height':
  578. menu.find('ul').last().height(parseInt(value, 10));
  579. break;
  580. case 'minWidth':
  581. this.options[key] = parseInt(value, 10);
  582. this._setButtonWidth();
  583. this._setMenuWidth();
  584. break;
  585. case 'selectedText':
  586. case 'selectedList':
  587. case 'noneSelectedText':
  588. this.options[key] = value; // these all needs to update immediately for the update() call
  589. this.update();
  590. break;
  591. case 'classes':
  592. menu.add(this.button).removeClass(this.options.classes).addClass(value);
  593. break;
  594. case 'multiple':
  595. menu.toggleClass('ui-multiselect-single', !value);
  596. this.options.multiple = value;
  597. this.element[0].multiple = value;
  598. this.refresh();
  599. break;
  600. case 'position':
  601. this.position();
  602. }
  603. $.Widget.prototype._setOption.apply(this, arguments);
  604. }
  605. });
  606. })(jQuery);