ui.multiselect.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /*
  2. * jQuery UI Multiselect
  3. *
  4. * Authors:
  5. * Michael Aufreiter (quasipartikel.at)
  6. * Yanick Rochon (yanick.rochon[at]gmail[dot]com)
  7. *
  8. * Dual licensed under the MIT (MIT-LICENSE.txt)
  9. * and GPL (GPL-LICENSE.txt) licenses.
  10. *
  11. * http://www.quasipartikel.at/multiselect/
  12. *
  13. *
  14. * Depends:
  15. * ui.core.js
  16. * ui.sortable.js
  17. *
  18. * Optional:
  19. * localization (http://plugins.jquery.com/project/localisation)
  20. * scrollTo (http://plugins.jquery.com/project/ScrollTo)
  21. *
  22. * Todo:
  23. * Make batch actions faster
  24. * Implement dynamic insertion through remote calls
  25. */
  26. (function($) {
  27. $.widget("ui.multiselect", {
  28. options: {
  29. sortable: true,
  30. searchable: true,
  31. doubleClickable: true,
  32. animated: 'fast',
  33. show: 'slideDown',
  34. hide: 'slideUp',
  35. dividerLocation: 0.6,
  36. availableFirst: false,
  37. nodeComparator: function(node1,node2) {
  38. var text1 = node1.text(),
  39. text2 = node2.text();
  40. return text1 == text2 ? 0 : (text1 < text2 ? -1 : 1);
  41. }
  42. },
  43. _create: function() {
  44. this.element.hide();
  45. this.id = this.element.attr("id");
  46. this.container = $('<div class="ui-multiselect ui-helper-clearfix ui-widget"></div>').insertAfter(this.element);
  47. this.count = 0; // number of currently selected options
  48. this.selectedContainer = $('<div class="selected"></div>').appendTo(this.container);
  49. this.availableContainer = $('<div class="available"></div>')[this.options.availableFirst?'prependTo': 'appendTo'](this.container);
  50. this.selectedActions = $('<div class="actions ui-widget-header ui-helper-clearfix"><span class="count">0 '+$.ui.multiselect.locale.itemsCount+'</span><a href="#" class="remove-all">'+$.ui.multiselect.locale.removeAll+'</a></div>').appendTo(this.selectedContainer);
  51. this.availableActions = $('<div class="actions ui-widget-header ui-helper-clearfix"><input type="text" class="search empty ui-widget-content ui-corner-all"/><a href="#" class="add-all">'+$.ui.multiselect.locale.addAll+'</a></div>').appendTo(this.availableContainer);
  52. this.selectedList = $('<ul class="selected connected-list"><li class="ui-helper-hidden-accessible"></li></ul>').bind('selectstart', function(){return false;}).appendTo(this.selectedContainer);
  53. this.availableList = $('<ul class="available connected-list"><li class="ui-helper-hidden-accessible"></li></ul>').bind('selectstart', function(){return false;}).appendTo(this.availableContainer);
  54. var that = this;
  55. // set dimensions
  56. this.container.width(this.element.width()+1);
  57. this.selectedContainer.width(Math.floor(this.element.width()*this.options.dividerLocation));
  58. this.availableContainer.width(Math.floor(this.element.width()*(1-this.options.dividerLocation)));
  59. // fix list height to match <option> depending on their individual header's heights
  60. this.selectedList.height(Math.max(this.element.height()-this.selectedActions.height(),1));
  61. this.availableList.height(Math.max(this.element.height()-this.availableActions.height(),1));
  62. if ( !this.options.animated ) {
  63. this.options.show = 'show';
  64. this.options.hide = 'hide';
  65. }
  66. this.useProp = !!$.fn.prop;
  67. // init lists
  68. this._populateLists(this.element.find('option'));
  69. // make selection sortable
  70. if (this.options.sortable) {
  71. this.selectedList.sortable({
  72. placeholder: 'ui-state-highlight',
  73. axis: 'y',
  74. update: function(event, ui) {
  75. // apply the new sort order to the original selectbox
  76. that.selectedList.find('li').each(function() {
  77. if ($(this).data('optionLink'))
  78. $(this).data('optionLink').remove().appendTo(that.element);
  79. });
  80. },
  81. receive: function(event, ui) {
  82. ui.item.data('optionLink')[ this.useProp ? 'prop' : 'attr' ]('selected', true);
  83. // increment count
  84. that.count += 1;
  85. that._updateCount();
  86. // workaround, because there's no way to reference
  87. // the new element, see http://dev.jqueryui.com/ticket/4303
  88. that.selectedList.children('.ui-draggable').each(function() {
  89. $(this).removeClass('ui-draggable');
  90. $(this).data('optionLink', ui.item.data('optionLink'));
  91. $(this).data('idx', ui.item.data('idx'));
  92. that._applyItemState($(this), true);
  93. });
  94. // workaround according to http://dev.jqueryui.com/ticket/4088
  95. setTimeout(function() { ui.item.remove(); }, 1);
  96. }
  97. });
  98. }
  99. // set up livesearch
  100. if (this.options.searchable) {
  101. this._registerSearchEvents(this.availableContainer.find('input.search'));
  102. } else {
  103. $('.search').hide();
  104. }
  105. // batch actions
  106. this.container.find(".remove-all").click(function() {
  107. that._populateLists(that.element.find('option').removeAttr('selected'));
  108. return false;
  109. });
  110. this.container.find(".add-all").click(function() {
  111. var options = that.element.find('option').not(":selected");
  112. if (that.availableList.children('li:hidden').length > 1) {
  113. that.availableList.children('li').each(function(i) {
  114. if ($(this).is(":visible")) $(options[i-1])[ that.useProp ? 'prop' : 'attr' ]('selected', true);
  115. });
  116. } else {
  117. options[ that.useProp ? 'prop' : 'attr' ]('selected', true);
  118. }
  119. that._populateLists(that.element.find('option'));
  120. return false;
  121. });
  122. },
  123. destroy: function() {
  124. this.element.show();
  125. this.container.remove();
  126. $.Widget.prototype.destroy.apply(this, arguments);
  127. },
  128. _populateLists: function(options) {
  129. this.selectedList.children('.ui-element').remove();
  130. this.availableList.children('.ui-element').remove();
  131. this.count = 0;
  132. var that = this;
  133. var items = $(options.map(function(i) {
  134. var item = that._getOptionNode(this).appendTo(this.selected ? that.selectedList : that.availableList).show();
  135. if (this.selected) that.count += 1;
  136. that._applyItemState(item, this.selected);
  137. item.data('idx', i);
  138. return item[0];
  139. }));
  140. // update count
  141. this._updateCount();
  142. that._filter.apply(this.availableContainer.find('input.search'), [that.availableList]);
  143. },
  144. _updateCount: function() {
  145. this.element.trigger('change');
  146. this.selectedContainer.find('span.count').text(this.count+" "+$.ui.multiselect.locale.itemsCount);
  147. },
  148. _getOptionNode: function(option) {
  149. option = $(option);
  150. var node = $('<li class="ui-state-default ui-element" title="'+option.text()+'"><span class="ui-icon"/>'+option.text()+'<a href="#" class="action"><span class="ui-corner-all ui-icon"/></a></li>').hide();
  151. node.data('optionLink', option);
  152. return node;
  153. },
  154. // clones an item with associated data
  155. // didn't find a smarter away around this
  156. _cloneWithData: function(clonee) {
  157. var clone = clonee.clone(false,false);
  158. clone.data('optionLink', clonee.data('optionLink'));
  159. clone.data('idx', clonee.data('idx'));
  160. return clone;
  161. },
  162. _setSelected: function(item, selected) {
  163. item.data('optionLink')[ this.useProp ? 'prop' : 'attr' ]('selected', selected);
  164. if (selected) {
  165. var selectedItem = this._cloneWithData(item);
  166. item[this.options.hide](this.options.animated, function() { $(this).remove(); });
  167. selectedItem.appendTo(this.selectedList).hide()[this.options.show](this.options.animated);
  168. this._applyItemState(selectedItem, true);
  169. return selectedItem;
  170. } else {
  171. // look for successor based on initial option index
  172. var items = this.availableList.find('li'), comparator = this.options.nodeComparator;
  173. var succ = null, i = item.data('idx'), direction = comparator(item, $(items[i]));
  174. // TODO: test needed for dynamic list populating
  175. if ( direction ) {
  176. while (i>=0 && i<items.length) {
  177. direction > 0 ? i++ : i--;
  178. if ( direction != comparator(item, $(items[i])) ) {
  179. // going up, go back one item down, otherwise leave as is
  180. succ = items[direction > 0 ? i : i+1];
  181. break;
  182. }
  183. }
  184. } else {
  185. succ = items[i];
  186. }
  187. var availableItem = this._cloneWithData(item);
  188. succ ? availableItem.insertBefore($(succ)) : availableItem.appendTo(this.availableList);
  189. item[this.options.hide](this.options.animated, function() { $(this).remove(); });
  190. availableItem.hide()[this.options.show](this.options.animated);
  191. this._applyItemState(availableItem, false);
  192. return availableItem;
  193. }
  194. },
  195. _applyItemState: function(item, selected) {
  196. if (selected) {
  197. if (this.options.sortable)
  198. item.children('span').addClass('ui-icon-arrowthick-2-n-s').removeClass('ui-helper-hidden').addClass('ui-icon');
  199. else
  200. item.children('span').removeClass('ui-icon-arrowthick-2-n-s').addClass('ui-helper-hidden').removeClass('ui-icon');
  201. item.find('a.action span').addClass('ui-icon-minus').removeClass('ui-icon-plus');
  202. this._registerRemoveEvents(item.find('a.action'));
  203. } else {
  204. item.children('span').removeClass('ui-icon-arrowthick-2-n-s').addClass('ui-helper-hidden').removeClass('ui-icon');
  205. item.find('a.action span').addClass('ui-icon-plus').removeClass('ui-icon-minus');
  206. this._registerAddEvents(item.find('a.action'));
  207. }
  208. this._registerDoubleClickEvents(item);
  209. this._registerHoverEvents(item);
  210. },
  211. // taken from John Resig's liveUpdate script
  212. _filter: function(list) {
  213. var input = $(this);
  214. var rows = list.children('li'),
  215. cache = rows.map(function(){
  216. return $(this).text().toLowerCase();
  217. });
  218. var term = $.trim(input.val().toLowerCase()), scores = [];
  219. if (!term) {
  220. rows.show();
  221. } else {
  222. rows.hide();
  223. cache.each(function(i) {
  224. if (this.indexOf(term)>-1) { scores.push(i); }
  225. });
  226. $.each(scores, function() {
  227. $(rows[this]).show();
  228. });
  229. }
  230. },
  231. _registerDoubleClickEvents: function(elements) {
  232. if (!this.options.doubleClickable) return;
  233. elements.dblclick(function(ev) {
  234. if ($(ev.target).closest('.action').length === 0) {
  235. // This may be triggered with rapid clicks on actions as well. In that
  236. // case don't trigger an additional click.
  237. elements.find('a.action').click();
  238. }
  239. });
  240. },
  241. _registerHoverEvents: function(elements) {
  242. elements.removeClass('ui-state-hover');
  243. elements.mouseover(function() {
  244. $(this).addClass('ui-state-hover');
  245. });
  246. elements.mouseout(function() {
  247. $(this).removeClass('ui-state-hover');
  248. });
  249. },
  250. _registerAddEvents: function(elements) {
  251. var that = this;
  252. elements.click(function() {
  253. var item = that._setSelected($(this).parent(), true);
  254. that.count += 1;
  255. that._updateCount();
  256. return false;
  257. });
  258. // make draggable
  259. if (this.options.sortable) {
  260. elements.each(function() {
  261. $(this).parent().draggable({
  262. connectToSortable: that.selectedList,
  263. helper: function() {
  264. var selectedItem = that._cloneWithData($(this)).width($(this).width() - 50);
  265. selectedItem.width($(this).width());
  266. return selectedItem;
  267. },
  268. appendTo: that.container,
  269. containment: that.container,
  270. revert: 'invalid'
  271. });
  272. });
  273. }
  274. },
  275. _registerRemoveEvents: function(elements) {
  276. var that = this;
  277. elements.click(function() {
  278. that._setSelected($(this).parent(), false);
  279. that.count -= 1;
  280. that._updateCount();
  281. return false;
  282. });
  283. },
  284. _registerSearchEvents: function(input) {
  285. var that = this;
  286. input.focus(function() {
  287. $(this).addClass('ui-state-active');
  288. })
  289. .blur(function() {
  290. $(this).removeClass('ui-state-active');
  291. })
  292. .keypress(function(e) {
  293. if (e.keyCode == 13)
  294. return false;
  295. })
  296. .keyup(function() {
  297. that._filter.apply(this, [that.availableList]);
  298. });
  299. }
  300. });
  301. $.extend($.ui.multiselect, {
  302. locale: {
  303. addAll:'Add all',
  304. removeAll:'Remove all',
  305. itemsCount:'items selected'
  306. }
  307. });
  308. })(jQuery);