jquery.multi-select.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. /*
  2. * MultiSelect v0.9.11
  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) options = [options];
  146. $.each(options, function(index, option){
  147. if (option.value && that.$element.find("option[value='"+option.value+"']").length === 0){
  148. var $option = $('<option value="'+option.value+'">'+option.text+'</option>'),
  149. index = parseInt((typeof option.index === 'undefined' ? that.$element.children().length : option.index)),
  150. $container = option.nested == undefined ? that.$element : $("optgroup[label='"+option.nested+"']")
  151. $option.insertAt(index, $container);
  152. that.generateLisFromOption($option.get(0), index, option.nested);
  153. }
  154. })
  155. },
  156. 'escapeHTML' : function(text){
  157. return $("<div>").text(text).html();
  158. },
  159. 'activeKeyboard' : function($list){
  160. var that = this;
  161. $list.on('focus', function(){
  162. $(this).addClass('ms-focus');
  163. })
  164. .on('blur', function(){
  165. $(this).removeClass('ms-focus');
  166. })
  167. .on('keydown', function(e){
  168. switch (e.which) {
  169. case 40:
  170. case 38:
  171. e.preventDefault();
  172. e.stopPropagation();
  173. that.moveHighlight($(this), (e.which === 38) ? -1 : 1);
  174. return;
  175. case 37:
  176. case 39:
  177. e.preventDefault();
  178. e.stopPropagation();
  179. that.switchList($list);
  180. return;
  181. case 9:
  182. if(that.$element.is('[tabindex]')){
  183. e.preventDefault();
  184. var tabindex = parseInt(that.$element.attr('tabindex'), 10);
  185. tabindex = (e.shiftKey) ? tabindex-1 : tabindex+1;
  186. $('[tabindex="'+(tabindex)+'"]').focus();
  187. return;
  188. }else{
  189. if(e.shiftKey){
  190. that.$element.trigger('focus');
  191. }
  192. }
  193. }
  194. if($.inArray(e.which, that.options.keySelect) > -1){
  195. e.preventDefault();
  196. e.stopPropagation();
  197. that.selectHighlighted($list);
  198. return;
  199. }
  200. });
  201. },
  202. 'moveHighlight': function($list, direction){
  203. var $elems = $list.find(this.elemsSelector),
  204. $currElem = $elems.filter('.ms-hover'),
  205. $nextElem = null,
  206. elemHeight = $elems.first().outerHeight(),
  207. containerHeight = $list.height(),
  208. containerSelector = '#'+this.$container.prop('id');
  209. $elems.removeClass('ms-hover');
  210. if (direction === 1){ // DOWN
  211. $nextElem = $currElem.nextAll(this.elemsSelector).first();
  212. if ($nextElem.length === 0){
  213. var $optgroupUl = $currElem.parent();
  214. if ($optgroupUl.hasClass('ms-optgroup')){
  215. var $optgroupLi = $optgroupUl.parent(),
  216. $nextOptgroupLi = $optgroupLi.next(':visible');
  217. if ($nextOptgroupLi.length > 0){
  218. $nextElem = $nextOptgroupLi.find(this.elemsSelector).first();
  219. } else {
  220. $nextElem = $elems.first();
  221. }
  222. } else {
  223. $nextElem = $elems.first();
  224. }
  225. }
  226. } else if (direction === -1){ // UP
  227. $nextElem = $currElem.prevAll(this.elemsSelector).first();
  228. if ($nextElem.length === 0){
  229. var $optgroupUl = $currElem.parent();
  230. if ($optgroupUl.hasClass('ms-optgroup')){
  231. var $optgroupLi = $optgroupUl.parent(),
  232. $prevOptgroupLi = $optgroupLi.prev(':visible');
  233. if ($prevOptgroupLi.length > 0){
  234. $nextElem = $prevOptgroupLi.find(this.elemsSelector).last();
  235. } else {
  236. $nextElem = $elems.last();
  237. }
  238. } else {
  239. $nextElem = $elems.last();
  240. }
  241. }
  242. }
  243. if ($nextElem.length > 0){
  244. $nextElem.addClass('ms-hover');
  245. var scrollTo = $list.scrollTop() + $nextElem.position().top -
  246. containerHeight / 2 + elemHeight / 2;
  247. $list.scrollTop(scrollTo);
  248. }
  249. },
  250. 'selectHighlighted' : function($list){
  251. var $elems = $list.find(this.elemsSelector),
  252. $highlightedElem = $elems.filter('.ms-hover').first();
  253. if ($highlightedElem.length > 0){
  254. if ($list.parent().hasClass('ms-selectable')){
  255. this.select($highlightedElem.data('ms-value'));
  256. } else {
  257. this.deselect($highlightedElem.data('ms-value'));
  258. }
  259. $elems.removeClass('ms-hover');
  260. }
  261. },
  262. 'switchList' : function($list){
  263. $list.blur();
  264. this.$container.find(this.elemsSelector).removeClass('ms-hover');
  265. if ($list.parent().hasClass('ms-selectable')){
  266. this.$selectionUl.focus();
  267. } else {
  268. this.$selectableUl.focus();
  269. }
  270. },
  271. 'activeMouse' : function($list){
  272. var that = this;
  273. $('body').on('mouseenter', that.elemsSelector, function(){
  274. $(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover');
  275. $(this).addClass('ms-hover');
  276. });
  277. $('body').on('mouseleave', that.elemsSelector, function () {
  278. $(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover');;
  279. });
  280. },
  281. 'refresh' : function() {
  282. this.destroy();
  283. this.$element.multiSelect(this.options);
  284. },
  285. 'destroy' : function(){
  286. $("#ms-"+this.$element.attr("id")).remove();
  287. this.$element.css('position', '').css('left', '')
  288. this.$element.removeData('multiselect');
  289. },
  290. 'select' : function(value, method){
  291. if (typeof value === 'string'){ value = [value]; }
  292. var that = this,
  293. ms = this.$element,
  294. msIds = $.map(value, function(val){ return(that.sanitize(val)); }),
  295. selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable').filter(':not(.'+that.options.disabledClass+')'),
  296. selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection').filter(':not(.'+that.options.disabledClass+')'),
  297. options = ms.find('option:not(:disabled)').filter(function(){ return($.inArray(this.value, value) > -1); });
  298. if (method === 'init'){
  299. selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),
  300. selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection');
  301. }
  302. if (selectables.length > 0){
  303. selectables.addClass('ms-selected').hide();
  304. selections.addClass('ms-selected').show();
  305. options.prop('selected', true);
  306. that.$container.find(that.elemsSelector).removeClass('ms-hover');
  307. var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
  308. if (selectableOptgroups.length > 0){
  309. selectableOptgroups.each(function(){
  310. var selectablesLi = $(this).find('.ms-elem-selectable');
  311. if (selectablesLi.length === selectablesLi.filter('.ms-selected').length){
  312. $(this).find('.ms-optgroup-label').hide();
  313. }
  314. });
  315. var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');
  316. selectionOptgroups.each(function(){
  317. var selectionsLi = $(this).find('.ms-elem-selection');
  318. if (selectionsLi.filter('.ms-selected').length > 0){
  319. $(this).find('.ms-optgroup-label').show();
  320. }
  321. });
  322. } else {
  323. if (that.options.keepOrder && method !== 'init'){
  324. var selectionLiLast = that.$selectionUl.find('.ms-selected');
  325. if((selectionLiLast.length > 1) && (selectionLiLast.last().get(0) != selections.get(0))) {
  326. selections.insertAfter(selectionLiLast.last());
  327. }
  328. }
  329. }
  330. if (method !== 'init'){
  331. ms.trigger('change');
  332. if (typeof that.options.afterSelect === 'function') {
  333. that.options.afterSelect.call(this, value);
  334. }
  335. }
  336. }
  337. },
  338. 'deselect' : function(value){
  339. if (typeof value === 'string'){ value = [value]; }
  340. var that = this,
  341. ms = this.$element,
  342. msIds = $.map(value, function(val){ return(that.sanitize(val)); }),
  343. selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),
  344. selections = this.$selectionUl.find('#' + msIds.join('-selection, #')+'-selection').filter('.ms-selected').filter(':not(.'+that.options.disabledClass+')'),
  345. options = ms.find('option').filter(function(){ return($.inArray(this.value, value) > -1); });
  346. if (selections.length > 0){
  347. selectables.removeClass('ms-selected').show();
  348. selections.removeClass('ms-selected').hide();
  349. options.prop('selected', false);
  350. that.$container.find(that.elemsSelector).removeClass('ms-hover');
  351. var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
  352. if (selectableOptgroups.length > 0){
  353. selectableOptgroups.each(function(){
  354. var selectablesLi = $(this).find('.ms-elem-selectable');
  355. if (selectablesLi.filter(':not(.ms-selected)').length > 0){
  356. $(this).find('.ms-optgroup-label').show();
  357. }
  358. });
  359. var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');
  360. selectionOptgroups.each(function(){
  361. var selectionsLi = $(this).find('.ms-elem-selection');
  362. if (selectionsLi.filter('.ms-selected').length === 0){
  363. $(this).find('.ms-optgroup-label').hide();
  364. }
  365. });
  366. }
  367. ms.trigger('change');
  368. if (typeof that.options.afterDeselect === 'function') {
  369. that.options.afterDeselect.call(this, value);
  370. }
  371. }
  372. },
  373. 'select_all' : function(){
  374. var ms = this.$element,
  375. values = ms.val();
  376. ms.find('option:not(":disabled")').prop('selected', true);
  377. this.$selectableUl.find('.ms-elem-selectable').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').hide();
  378. this.$selectionUl.find('.ms-optgroup-label').show();
  379. this.$selectableUl.find('.ms-optgroup-label').hide();
  380. this.$selectionUl.find('.ms-elem-selection').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').show();
  381. this.$selectionUl.focus();
  382. ms.trigger('change');
  383. if (typeof this.options.afterSelect === 'function') {
  384. var selectedValues = $.grep(ms.val(), function(item){
  385. return $.inArray(item, values) < 0;
  386. });
  387. this.options.afterSelect.call(this, selectedValues);
  388. }
  389. },
  390. 'deselect_all' : function(){
  391. var ms = this.$element,
  392. values = ms.val();
  393. ms.find('option').prop('selected', false);
  394. this.$selectableUl.find('.ms-elem-selectable').removeClass('ms-selected').show();
  395. this.$selectionUl.find('.ms-optgroup-label').hide();
  396. this.$selectableUl.find('.ms-optgroup-label').show();
  397. this.$selectionUl.find('.ms-elem-selection').removeClass('ms-selected').hide();
  398. this.$selectableUl.focus();
  399. ms.trigger('change');
  400. if (typeof this.options.afterDeselect === 'function') {
  401. this.options.afterDeselect.call(this, values);
  402. }
  403. },
  404. sanitize: function(value){
  405. var hash = 0, i, character;
  406. if (value.length == 0) return hash;
  407. var ls = 0;
  408. for (i = 0, ls = value.length; i < ls; i++) {
  409. character = value.charCodeAt(i);
  410. hash = ((hash<<5)-hash)+character;
  411. hash |= 0; // Convert to 32bit integer
  412. }
  413. return hash;
  414. }
  415. };
  416. /* MULTISELECT PLUGIN DEFINITION
  417. * ======================= */
  418. $.fn.multiSelect = function () {
  419. var option = arguments[0],
  420. args = arguments;
  421. return this.each(function () {
  422. var $this = $(this),
  423. data = $this.data('multiselect'),
  424. options = $.extend({}, $.fn.multiSelect.defaults, $this.data(), typeof option === 'object' && option);
  425. if (!data){ $this.data('multiselect', (data = new MultiSelect(this, options))); }
  426. if (typeof option === 'string'){
  427. data[option](args[1]);
  428. } else {
  429. data.init();
  430. }
  431. });
  432. };
  433. $.fn.multiSelect.defaults = {
  434. keySelect: [32],
  435. selectableOptgroup: false,
  436. disabledClass : 'disabled',
  437. dblClick : false,
  438. keepOrder: false,
  439. cssClass: ''
  440. };
  441. $.fn.multiSelect.Constructor = MultiSelect;
  442. $.fn.insertAt = function(index, $parent) {
  443. return this.each(function() {
  444. if (index === 0) {
  445. $parent.prepend(this);
  446. } else {
  447. $parent.children().eq(index - 1).after(this);
  448. }
  449. });
  450. }
  451. }(window.jQuery);