jquery.multi-select.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. /*
  2. * MultiSelect v0.9.12
  3. * Copyright (c) 2012 Louis Cuny
  4. *
  5. * This program is free software. It comes without any warranty, to
  6. * the extent permitted by applicable law. You can redistribute it
  7. * and/or modify it under the terms of the Do What The Fuck You Want
  8. * To Public License, Version 2, as published by Sam Hocevar. See
  9. * http://sam.zoy.org/wtfpl/COPYING for more details.
  10. */
  11. !function ($) {
  12. "use strict";
  13. /* MULTISELECT CLASS DEFINITION
  14. * ====================== */
  15. var MultiSelect = function (element, options) {
  16. this.options = options;
  17. this.$element = $(element);
  18. this.$container = $('<div/>', { 'class': "ms-container" });
  19. this.$selectableContainer = $('<div/>', { 'class': 'ms-selectable' });
  20. this.$selectionContainer = $('<div/>', { 'class': 'ms-selection' });
  21. this.$selectableUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' });
  22. this.$selectionUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' });
  23. this.scrollTo = 0;
  24. this.elemsSelector = 'li:visible:not(.ms-optgroup-label,.ms-optgroup-container,.'+options.disabledClass+')';
  25. };
  26. MultiSelect.prototype = {
  27. constructor: MultiSelect,
  28. init: function(){
  29. var that = this,
  30. ms = this.$element;
  31. if (ms.next('.ms-container').length === 0){
  32. ms.css({ position: 'absolute', left: '-9999px' });
  33. ms.attr('id', ms.attr('id') ? ms.attr('id') : Math.ceil(Math.random()*1000)+'multiselect');
  34. this.$container.attr('id', 'ms-'+ms.attr('id'));
  35. this.$container.addClass(that.options.cssClass);
  36. ms.find('option').each(function(){
  37. that.generateLisFromOption(this);
  38. });
  39. this.$selectionUl.find('.ms-optgroup-label').hide();
  40. if (that.options.selectableHeader){
  41. that.$selectableContainer.append(that.options.selectableHeader);
  42. }
  43. that.$selectableContainer.append(that.$selectableUl);
  44. if (that.options.selectableFooter){
  45. that.$selectableContainer.append(that.options.selectableFooter);
  46. }
  47. if (that.options.selectionHeader){
  48. that.$selectionContainer.append(that.options.selectionHeader);
  49. }
  50. that.$selectionContainer.append(that.$selectionUl);
  51. if (that.options.selectionFooter){
  52. that.$selectionContainer.append(that.options.selectionFooter);
  53. }
  54. that.$container.append(that.$selectableContainer);
  55. that.$container.append(that.$selectionContainer);
  56. ms.after(that.$container);
  57. that.activeMouse(that.$selectableUl);
  58. that.activeKeyboard(that.$selectableUl);
  59. var action = that.options.dblClick ? 'dblclick' : 'click';
  60. that.$selectableUl.on(action, '.ms-elem-selectable', function(){
  61. that.select($(this).data('ms-value'));
  62. });
  63. that.$selectionUl.on(action, '.ms-elem-selection', function(){
  64. that.deselect($(this).data('ms-value'));
  65. });
  66. that.activeMouse(that.$selectionUl);
  67. that.activeKeyboard(that.$selectionUl);
  68. ms.on('focus', function(){
  69. that.$selectableUl.focus();
  70. });
  71. }
  72. var selectedValues = ms.find('option:selected').map(function(){ return $(this).val(); }).get();
  73. that.select(selectedValues, 'init');
  74. if (typeof that.options.afterInit === 'function') {
  75. that.options.afterInit.call(this, this.$container);
  76. }
  77. },
  78. 'generateLisFromOption' : function(option, index, $container){
  79. var that = this,
  80. ms = that.$element,
  81. attributes = "",
  82. $option = $(option);
  83. for (var cpt = 0; cpt < option.attributes.length; cpt++){
  84. var attr = option.attributes[cpt];
  85. if(attr.name !== 'value' && attr.name !== 'disabled'){
  86. attributes += attr.name+'="'+attr.value+'" ';
  87. }
  88. }
  89. var selectableLi = $('<li '+attributes+'><span>'+that.escapeHTML($option.text())+'</span></li>'),
  90. selectedLi = selectableLi.clone(),
  91. value = $option.val(),
  92. elementId = that.sanitize(value);
  93. selectableLi
  94. .data('ms-value', value)
  95. .addClass('ms-elem-selectable')
  96. .attr('id', elementId+'-selectable');
  97. selectedLi
  98. .data('ms-value', value)
  99. .addClass('ms-elem-selection')
  100. .attr('id', elementId+'-selection')
  101. .hide();
  102. if ($option.prop('disabled') || ms.prop('disabled')){
  103. selectedLi.addClass(that.options.disabledClass);
  104. selectableLi.addClass(that.options.disabledClass);
  105. }
  106. var $optgroup = $option.parent('optgroup');
  107. if ($optgroup.length > 0){
  108. var optgroupLabel = $optgroup.attr('label'),
  109. optgroupId = that.sanitize(optgroupLabel),
  110. $selectableOptgroup = that.$selectableUl.find('#optgroup-selectable-'+optgroupId),
  111. $selectionOptgroup = that.$selectionUl.find('#optgroup-selection-'+optgroupId);
  112. if ($selectableOptgroup.length === 0){
  113. var optgroupContainerTpl = '<li class="ms-optgroup-container"></li>',
  114. optgroupTpl = '<ul class="ms-optgroup"><li class="ms-optgroup-label"><span>'+optgroupLabel+'</span></li></ul>';
  115. $selectableOptgroup = $(optgroupContainerTpl);
  116. $selectionOptgroup = $(optgroupContainerTpl);
  117. $selectableOptgroup.attr('id', 'optgroup-selectable-'+optgroupId);
  118. $selectionOptgroup.attr('id', 'optgroup-selection-'+optgroupId);
  119. $selectableOptgroup.append($(optgroupTpl));
  120. $selectionOptgroup.append($(optgroupTpl));
  121. if (that.options.selectableOptgroup){
  122. $selectableOptgroup.find('.ms-optgroup-label').on('click', function(){
  123. var values = $optgroup.children(':not(:selected, :disabled)').map(function(){ return $(this).val();}).get();
  124. that.select(values);
  125. });
  126. $selectionOptgroup.find('.ms-optgroup-label').on('click', function(){
  127. var values = $optgroup.children(':selected:not(:disabled)').map(function(){ return $(this).val();}).get();
  128. that.deselect(values);
  129. });
  130. }
  131. that.$selectableUl.append($selectableOptgroup);
  132. that.$selectionUl.append($selectionOptgroup);
  133. }
  134. index = index === undefined ? $selectableOptgroup.find('ul').children().length : index + 1;
  135. selectableLi.insertAt(index, $selectableOptgroup.children());
  136. selectedLi.insertAt(index, $selectionOptgroup.children());
  137. } else {
  138. index = index === undefined ? that.$selectableUl.children().length : index;
  139. selectableLi.insertAt(index, that.$selectableUl);
  140. selectedLi.insertAt(index, that.$selectionUl);
  141. }
  142. },
  143. 'addOption' : function(options){
  144. var that = this;
  145. if (options.value !== undefined && options.value !== null){
  146. options = [options];
  147. }
  148. $.each(options, function(index, option){
  149. if (option.value !== undefined && option.value !== null &&
  150. that.$element.find("option[value='"+option.value+"']").length === 0){
  151. var $option = $('<option value="'+option.value+'">'+option.text+'</option>'),
  152. index = parseInt((typeof option.index === 'undefined' ? that.$element.children().length : option.index)),
  153. $container = option.nested === undefined ? that.$element : $("optgroup[label='"+option.nested+"']");
  154. $option.insertAt(index, $container);
  155. that.generateLisFromOption($option.get(0), index, option.nested);
  156. }
  157. });
  158. },
  159. 'escapeHTML' : function(text){
  160. return $("<div>").text(text).html();
  161. },
  162. 'activeKeyboard' : function($list){
  163. var that = this;
  164. $list.on('focus', function(){
  165. $(this).addClass('ms-focus');
  166. })
  167. .on('blur', function(){
  168. $(this).removeClass('ms-focus');
  169. })
  170. .on('keydown', function(e){
  171. switch (e.which) {
  172. case 40:
  173. case 38:
  174. e.preventDefault();
  175. e.stopPropagation();
  176. that.moveHighlight($(this), (e.which === 38) ? -1 : 1);
  177. return;
  178. case 37:
  179. case 39:
  180. e.preventDefault();
  181. e.stopPropagation();
  182. that.switchList($list);
  183. return;
  184. case 9:
  185. if(that.$element.is('[tabindex]')){
  186. e.preventDefault();
  187. var tabindex = parseInt(that.$element.attr('tabindex'), 10);
  188. tabindex = (e.shiftKey) ? tabindex-1 : tabindex+1;
  189. $('[tabindex="'+(tabindex)+'"]').focus();
  190. return;
  191. }else{
  192. if(e.shiftKey){
  193. that.$element.trigger('focus');
  194. }
  195. }
  196. }
  197. if($.inArray(e.which, that.options.keySelect) > -1){
  198. e.preventDefault();
  199. e.stopPropagation();
  200. that.selectHighlighted($list);
  201. return;
  202. }
  203. });
  204. },
  205. 'moveHighlight': function($list, direction){
  206. var $elems = $list.find(this.elemsSelector),
  207. $currElem = $elems.filter('.ms-hover'),
  208. $nextElem = null,
  209. elemHeight = $elems.first().outerHeight(),
  210. containerHeight = $list.height(),
  211. containerSelector = '#'+this.$container.prop('id');
  212. $elems.removeClass('ms-hover');
  213. if (direction === 1){ // DOWN
  214. $nextElem = $currElem.nextAll(this.elemsSelector).first();
  215. if ($nextElem.length === 0){
  216. var $optgroupUl = $currElem.parent();
  217. if ($optgroupUl.hasClass('ms-optgroup')){
  218. var $optgroupLi = $optgroupUl.parent(),
  219. $nextOptgroupLi = $optgroupLi.next(':visible');
  220. if ($nextOptgroupLi.length > 0){
  221. $nextElem = $nextOptgroupLi.find(this.elemsSelector).first();
  222. } else {
  223. $nextElem = $elems.first();
  224. }
  225. } else {
  226. $nextElem = $elems.first();
  227. }
  228. }
  229. } else if (direction === -1){ // UP
  230. $nextElem = $currElem.prevAll(this.elemsSelector).first();
  231. if ($nextElem.length === 0){
  232. var $optgroupUl = $currElem.parent();
  233. if ($optgroupUl.hasClass('ms-optgroup')){
  234. var $optgroupLi = $optgroupUl.parent(),
  235. $prevOptgroupLi = $optgroupLi.prev(':visible');
  236. if ($prevOptgroupLi.length > 0){
  237. $nextElem = $prevOptgroupLi.find(this.elemsSelector).last();
  238. } else {
  239. $nextElem = $elems.last();
  240. }
  241. } else {
  242. $nextElem = $elems.last();
  243. }
  244. }
  245. }
  246. if ($nextElem.length > 0){
  247. $nextElem.addClass('ms-hover');
  248. var scrollTo = $list.scrollTop() + $nextElem.position().top -
  249. containerHeight / 2 + elemHeight / 2;
  250. $list.scrollTop(scrollTo);
  251. }
  252. },
  253. 'selectHighlighted' : function($list){
  254. var $elems = $list.find(this.elemsSelector),
  255. $highlightedElem = $elems.filter('.ms-hover').first();
  256. if ($highlightedElem.length > 0){
  257. if ($list.parent().hasClass('ms-selectable')){
  258. this.select($highlightedElem.data('ms-value'));
  259. } else {
  260. this.deselect($highlightedElem.data('ms-value'));
  261. }
  262. $elems.removeClass('ms-hover');
  263. }
  264. },
  265. 'switchList' : function($list){
  266. $list.blur();
  267. this.$container.find(this.elemsSelector).removeClass('ms-hover');
  268. if ($list.parent().hasClass('ms-selectable')){
  269. this.$selectionUl.focus();
  270. } else {
  271. this.$selectableUl.focus();
  272. }
  273. },
  274. 'activeMouse' : function($list){
  275. var that = this;
  276. this.$container.on('mouseenter', that.elemsSelector, function(){
  277. $(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover');
  278. $(this).addClass('ms-hover');
  279. });
  280. this.$container.on('mouseleave', that.elemsSelector, function () {
  281. $(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover');
  282. });
  283. },
  284. 'refresh' : function() {
  285. this.destroy();
  286. this.$element.multiSelect(this.options);
  287. },
  288. 'destroy' : function(){
  289. $("#ms-"+this.$element.attr("id")).remove();
  290. this.$element.off('focus');
  291. this.$element.css('position', '').css('left', '');
  292. this.$element.removeData('multiselect');
  293. },
  294. 'select' : function(value, method){
  295. if (typeof value === 'string'){ value = [value]; }
  296. var that = this,
  297. ms = this.$element,
  298. msIds = $.map(value, function(val){ return(that.sanitize(val)); }),
  299. selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable').filter(':not(.'+that.options.disabledClass+')'),
  300. selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection').filter(':not(.'+that.options.disabledClass+')'),
  301. options = ms.find('option:not(:disabled)').filter(function(){ return($.inArray(this.value, value) > -1); });
  302. if (method === 'init'){
  303. selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),
  304. selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection');
  305. }
  306. if (selectables.length > 0){
  307. selectables.addClass('ms-selected').hide();
  308. selections.addClass('ms-selected').show();
  309. options.prop('selected', true);
  310. that.$container.find(that.elemsSelector).removeClass('ms-hover');
  311. var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
  312. if (selectableOptgroups.length > 0){
  313. selectableOptgroups.each(function(){
  314. var selectablesLi = $(this).find('.ms-elem-selectable');
  315. if (selectablesLi.length === selectablesLi.filter('.ms-selected').length){
  316. $(this).find('.ms-optgroup-label').hide();
  317. }
  318. });
  319. var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');
  320. selectionOptgroups.each(function(){
  321. var selectionsLi = $(this).find('.ms-elem-selection');
  322. if (selectionsLi.filter('.ms-selected').length > 0){
  323. $(this).find('.ms-optgroup-label').show();
  324. }
  325. });
  326. } else {
  327. if (that.options.keepOrder && method !== 'init'){
  328. var selectionLiLast = that.$selectionUl.find('.ms-selected');
  329. if((selectionLiLast.length > 1) && (selectionLiLast.last().get(0) != selections.get(0))) {
  330. selections.insertAfter(selectionLiLast.last());
  331. }
  332. }
  333. }
  334. if (method !== 'init'){
  335. ms.trigger('change');
  336. if (typeof that.options.afterSelect === 'function') {
  337. that.options.afterSelect.call(this, value);
  338. }
  339. }
  340. }
  341. },
  342. 'deselect' : function(value){
  343. if (typeof value === 'string'){ value = [value]; }
  344. var that = this,
  345. ms = this.$element,
  346. msIds = $.map(value, function(val){ return(that.sanitize(val)); }),
  347. selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),
  348. selections = this.$selectionUl.find('#' + msIds.join('-selection, #')+'-selection').filter('.ms-selected').filter(':not(.'+that.options.disabledClass+')'),
  349. options = ms.find('option').filter(function(){ return($.inArray(this.value, value) > -1); });
  350. if (selections.length > 0){
  351. selectables.removeClass('ms-selected').show();
  352. selections.removeClass('ms-selected').hide();
  353. options.prop('selected', false);
  354. that.$container.find(that.elemsSelector).removeClass('ms-hover');
  355. var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
  356. if (selectableOptgroups.length > 0){
  357. selectableOptgroups.each(function(){
  358. var selectablesLi = $(this).find('.ms-elem-selectable');
  359. if (selectablesLi.filter(':not(.ms-selected)').length > 0){
  360. $(this).find('.ms-optgroup-label').show();
  361. }
  362. });
  363. var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');
  364. selectionOptgroups.each(function(){
  365. var selectionsLi = $(this).find('.ms-elem-selection');
  366. if (selectionsLi.filter('.ms-selected').length === 0){
  367. $(this).find('.ms-optgroup-label').hide();
  368. }
  369. });
  370. }
  371. ms.trigger('change');
  372. if (typeof that.options.afterDeselect === 'function') {
  373. that.options.afterDeselect.call(this, value);
  374. }
  375. }
  376. },
  377. 'select_all' : function(){
  378. var ms = this.$element,
  379. values = ms.val();
  380. ms.find('option:not(":disabled")').prop('selected', true);
  381. this.$selectableUl.find('.ms-elem-selectable').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').hide();
  382. this.$selectionUl.find('.ms-optgroup-label').show();
  383. this.$selectableUl.find('.ms-optgroup-label').hide();
  384. this.$selectionUl.find('.ms-elem-selection').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').show();
  385. this.$selectionUl.focus();
  386. ms.trigger('change');
  387. if (typeof this.options.afterSelect === 'function') {
  388. var selectedValues = $.grep(ms.val(), function(item){
  389. return $.inArray(item, values) < 0;
  390. });
  391. this.options.afterSelect.call(this, selectedValues);
  392. }
  393. },
  394. 'deselect_all' : function(){
  395. var ms = this.$element,
  396. values = ms.val();
  397. ms.find('option').prop('selected', false);
  398. this.$selectableUl.find('.ms-elem-selectable').removeClass('ms-selected').show();
  399. this.$selectionUl.find('.ms-optgroup-label').hide();
  400. this.$selectableUl.find('.ms-optgroup-label').show();
  401. this.$selectionUl.find('.ms-elem-selection').removeClass('ms-selected').hide();
  402. this.$selectableUl.focus();
  403. ms.trigger('change');
  404. if (typeof this.options.afterDeselect === 'function') {
  405. this.options.afterDeselect.call(this, values);
  406. }
  407. },
  408. sanitize: function(value){
  409. var hash = 0, i, character;
  410. if (value.length == 0) return hash;
  411. var ls = 0;
  412. for (i = 0, ls = value.length; i < ls; i++) {
  413. character = value.charCodeAt(i);
  414. hash = ((hash<<5)-hash)+character;
  415. hash |= 0; // Convert to 32bit integer
  416. }
  417. return hash;
  418. }
  419. };
  420. /* MULTISELECT PLUGIN DEFINITION
  421. * ======================= */
  422. $.fn.multiSelect = function () {
  423. var option = arguments[0],
  424. args = arguments;
  425. return this.each(function () {
  426. var $this = $(this),
  427. data = $this.data('multiselect'),
  428. options = $.extend({}, $.fn.multiSelect.defaults, $this.data(), typeof option === 'object' && option);
  429. if (!data){ $this.data('multiselect', (data = new MultiSelect(this, options))); }
  430. if (typeof option === 'string'){
  431. data[option](args[1]);
  432. } else {
  433. data.init();
  434. }
  435. });
  436. };
  437. $.fn.multiSelect.defaults = {
  438. keySelect: [32],
  439. selectableOptgroup: false,
  440. disabledClass : 'disabled',
  441. dblClick : false,
  442. keepOrder: false,
  443. cssClass: ''
  444. };
  445. $.fn.multiSelect.Constructor = MultiSelect;
  446. $.fn.insertAt = function(index, $parent) {
  447. return this.each(function() {
  448. if (index === 0) {
  449. $parent.prepend(this);
  450. } else {
  451. $parent.children().eq(index - 1).after(this);
  452. }
  453. });
  454. };
  455. }(window.jQuery);