jquery.multi-select.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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.css('position', '').css('left', '')
  291. this.$element.removeData('multiselect');
  292. },
  293. 'select' : function(value, method){
  294. if (typeof value === 'string'){ value = [value]; }
  295. var that = this,
  296. ms = this.$element,
  297. msIds = $.map(value, function(val){ return(that.sanitize(val)); }),
  298. selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable').filter(':not(.'+that.options.disabledClass+')'),
  299. selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection').filter(':not(.'+that.options.disabledClass+')'),
  300. options = ms.find('option:not(:disabled)').filter(function(){ return($.inArray(this.value, value) > -1); });
  301. if (method === 'init'){
  302. selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),
  303. selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection');
  304. }
  305. if (selectables.length > 0){
  306. selectables.addClass('ms-selected').hide();
  307. selections.addClass('ms-selected').show();
  308. options.prop('selected', true);
  309. that.$container.find(that.elemsSelector).removeClass('ms-hover');
  310. var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
  311. if (selectableOptgroups.length > 0){
  312. selectableOptgroups.each(function(){
  313. var selectablesLi = $(this).find('.ms-elem-selectable');
  314. if (selectablesLi.length === selectablesLi.filter('.ms-selected').length){
  315. $(this).find('.ms-optgroup-label').hide();
  316. }
  317. });
  318. var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');
  319. selectionOptgroups.each(function(){
  320. var selectionsLi = $(this).find('.ms-elem-selection');
  321. if (selectionsLi.filter('.ms-selected').length > 0){
  322. $(this).find('.ms-optgroup-label').show();
  323. }
  324. });
  325. } else {
  326. if (that.options.keepOrder && method !== 'init'){
  327. var selectionLiLast = that.$selectionUl.find('.ms-selected');
  328. if((selectionLiLast.length > 1) && (selectionLiLast.last().get(0) != selections.get(0))) {
  329. selections.insertAfter(selectionLiLast.last());
  330. }
  331. }
  332. }
  333. if (method !== 'init'){
  334. ms.trigger('change');
  335. if (typeof that.options.afterSelect === 'function') {
  336. that.options.afterSelect.call(this, value);
  337. }
  338. }
  339. }
  340. },
  341. 'deselect' : function(value){
  342. if (typeof value === 'string'){ value = [value]; }
  343. var that = this,
  344. ms = this.$element,
  345. msIds = $.map(value, function(val){ return(that.sanitize(val)); }),
  346. selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),
  347. selections = this.$selectionUl.find('#' + msIds.join('-selection, #')+'-selection').filter('.ms-selected').filter(':not(.'+that.options.disabledClass+')'),
  348. options = ms.find('option').filter(function(){ return($.inArray(this.value, value) > -1); });
  349. if (selections.length > 0){
  350. selectables.removeClass('ms-selected').show();
  351. selections.removeClass('ms-selected').hide();
  352. options.prop('selected', false);
  353. that.$container.find(that.elemsSelector).removeClass('ms-hover');
  354. var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
  355. if (selectableOptgroups.length > 0){
  356. selectableOptgroups.each(function(){
  357. var selectablesLi = $(this).find('.ms-elem-selectable');
  358. if (selectablesLi.filter(':not(.ms-selected)').length > 0){
  359. $(this).find('.ms-optgroup-label').show();
  360. }
  361. });
  362. var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');
  363. selectionOptgroups.each(function(){
  364. var selectionsLi = $(this).find('.ms-elem-selection');
  365. if (selectionsLi.filter('.ms-selected').length === 0){
  366. $(this).find('.ms-optgroup-label').hide();
  367. }
  368. });
  369. }
  370. ms.trigger('change');
  371. if (typeof that.options.afterDeselect === 'function') {
  372. that.options.afterDeselect.call(this, value);
  373. }
  374. }
  375. },
  376. 'select_all' : function(){
  377. var ms = this.$element,
  378. values = ms.val();
  379. ms.find('option:not(":disabled")').prop('selected', true);
  380. this.$selectableUl.find('.ms-elem-selectable').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').hide();
  381. this.$selectionUl.find('.ms-optgroup-label').show();
  382. this.$selectableUl.find('.ms-optgroup-label').hide();
  383. this.$selectionUl.find('.ms-elem-selection').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').show();
  384. this.$selectionUl.focus();
  385. ms.trigger('change');
  386. if (typeof this.options.afterSelect === 'function') {
  387. var selectedValues = $.grep(ms.val(), function(item){
  388. return $.inArray(item, values) < 0;
  389. });
  390. this.options.afterSelect.call(this, selectedValues);
  391. }
  392. },
  393. 'deselect_all' : function(){
  394. var ms = this.$element,
  395. values = ms.val();
  396. ms.find('option').prop('selected', false);
  397. this.$selectableUl.find('.ms-elem-selectable').removeClass('ms-selected').show();
  398. this.$selectionUl.find('.ms-optgroup-label').hide();
  399. this.$selectableUl.find('.ms-optgroup-label').show();
  400. this.$selectionUl.find('.ms-elem-selection').removeClass('ms-selected').hide();
  401. this.$selectableUl.focus();
  402. ms.trigger('change');
  403. if (typeof this.options.afterDeselect === 'function') {
  404. this.options.afterDeselect.call(this, values);
  405. }
  406. },
  407. sanitize: function(value){
  408. var hash = 0, i, character;
  409. if (value.length == 0) return hash;
  410. var ls = 0;
  411. for (i = 0, ls = value.length; i < ls; i++) {
  412. character = value.charCodeAt(i);
  413. hash = ((hash<<5)-hash)+character;
  414. hash |= 0; // Convert to 32bit integer
  415. }
  416. return hash;
  417. }
  418. };
  419. /* MULTISELECT PLUGIN DEFINITION
  420. * ======================= */
  421. $.fn.multiSelect = function () {
  422. var option = arguments[0],
  423. args = arguments;
  424. return this.each(function () {
  425. var $this = $(this),
  426. data = $this.data('multiselect'),
  427. options = $.extend({}, $.fn.multiSelect.defaults, $this.data(), typeof option === 'object' && option);
  428. if (!data){ $this.data('multiselect', (data = new MultiSelect(this, options))); }
  429. if (typeof option === 'string'){
  430. data[option](args[1]);
  431. } else {
  432. data.init();
  433. }
  434. });
  435. };
  436. $.fn.multiSelect.defaults = {
  437. keySelect: [32],
  438. selectableOptgroup: false,
  439. disabledClass : 'disabled',
  440. dblClick : false,
  441. keepOrder: false,
  442. cssClass: ''
  443. };
  444. $.fn.multiSelect.Constructor = MultiSelect;
  445. $.fn.insertAt = function(index, $parent) {
  446. return this.each(function() {
  447. if (index === 0) {
  448. $parent.prepend(this);
  449. } else {
  450. $parent.children().eq(index - 1).after(this);
  451. }
  452. });
  453. }
  454. }(window.jQuery);