multiselect.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /**
  2. * @param 'createCallback' A function to be called when a new entry is created.
  3. * Two arguments are supplied to this function:
  4. * The select element used and the value of the option. If the function
  5. * returns false addition will be cancelled. If it returns
  6. * anything else it will be used as the value of the newly added option.
  7. * @param 'createText' The placeholder text for the create action.
  8. * @param 'title' The title to show if no options are selected.
  9. * @param 'checked' An array containing values for options that should be
  10. * checked. Any options which are already selected will be added to this array.
  11. * @param 'labels' The corresponding labels to show for the checked items.
  12. * @param 'oncheck' Callback function which will be called when a
  13. * checkbox/radiobutton is selected. If the function returns false the input will be unchecked.
  14. * @param 'onuncheck' @see 'oncheck'.
  15. * @param 'singleSelect' If true radiobuttons will be used instead of
  16. * checkboxes.
  17. */
  18. (function( $ ){
  19. var multiSelectId=-1;
  20. $.fn.multiSelect=function(options) {
  21. multiSelectId++;
  22. var settings = {
  23. 'createCallback':false,
  24. 'createText':false,
  25. 'singleSelect':false,
  26. 'selectedFirst':false,
  27. 'sort':true,
  28. 'title':this.attr('title'),
  29. 'checked':[],
  30. 'labels':[],
  31. 'oncheck':false,
  32. 'onuncheck':false,
  33. 'minWidth': 'default;'
  34. };
  35. var slideDuration = 0;
  36. $(this).attr('data-msid', multiSelectId);
  37. $.extend(settings,options);
  38. $.each(this.children(),function(i,option) {
  39. // If the option is selected, but not in the checked array, add it.
  40. if (
  41. $(option).attr('selected') &&
  42. settings.checked.indexOf($(option).val()) === -1
  43. ) {
  44. settings.checked.push($(option).val());
  45. settings.labels.push($(option).text().trim());
  46. }
  47. // If the option is in the checked array but not selected, select it.
  48. else if (
  49. settings.checked.indexOf($(option).val()) !== -1 &&
  50. !$(option).attr('selected')
  51. ) {
  52. $(option).attr('selected', 'selected');
  53. settings.labels.push($(option).text().trim());
  54. }
  55. });
  56. var button=$('<div class="multiselect button"><span>'+settings.title+'</span><span class="icon-triangle-s"></span></div>');
  57. var span=$('<span/>');
  58. span.append(button);
  59. button.data('id',multiSelectId);
  60. button.selectedItems=[];
  61. this.hide();
  62. this.before(span);
  63. if(settings.minWidth=='default') {
  64. settings.minWidth=button.width();
  65. }
  66. button.css('min-width',settings.minWidth);
  67. settings.minOuterWidth=button.outerWidth()-2;
  68. button.data('settings',settings);
  69. if(!settings.singleSelect && settings.checked.length>0) {
  70. button.children('span').first().text(settings.labels.join(', '));
  71. } else if(settings.singleSelect) {
  72. button.children('span').first().text(this.find(':selected').text());
  73. }
  74. var self = this;
  75. self.menuDirection = 'down';
  76. function closeDropDown() {
  77. if(!button.parent().data('preventHide')) {
  78. // How can I save the effect in a var?
  79. if(self.menuDirection === 'down') {
  80. button.parent().children('ul').slideUp(slideDuration,function() {
  81. button.parent().children('ul').remove();
  82. button.removeClass('active down');
  83. $(self).trigger($.Event('dropdownclosed', settings));
  84. });
  85. } else {
  86. button.parent().children('ul').fadeOut(slideDuration,function() {
  87. button.parent().children('ul').remove();
  88. button.removeClass('active up');
  89. $(self).trigger($.Event('dropdownclosed', settings));
  90. });
  91. }
  92. }
  93. }
  94. button.click(function(event){
  95. var button=$(this);
  96. if(button.parent().children('ul').length>0) {
  97. if(self.menuDirection === 'down') {
  98. button.parent().children('ul').slideUp(slideDuration,function() {
  99. button.parent().children('ul').remove();
  100. button.removeClass('active down');
  101. $(self).trigger($.Event('dropdownclosed', settings));
  102. });
  103. } else {
  104. button.parent().children('ul').fadeOut(slideDuration,function() {
  105. button.parent().children('ul').remove();
  106. button.removeClass('active up');
  107. $(self).trigger($.Event('dropdownclosed', settings));
  108. });
  109. }
  110. return;
  111. }
  112. // tell other lists to shut themselves
  113. var lists=$('ul.multiselectoptions');
  114. lists.trigger($.Event('shut'));
  115. button.addClass('active');
  116. event.stopPropagation();
  117. var options=$(this).parent().next().children();
  118. var list=$('<ul class="multiselectoptions"/>').hide().appendTo($(this).parent());
  119. var inputType = settings.singleSelect ? 'radio' : 'checkbox';
  120. function createItem(element, checked){
  121. element=$(element);
  122. var item=element.val();
  123. var id='ms'+multiSelectId+'-option-'+item;
  124. var input=$('<input type="' + inputType + '"/>');
  125. input.attr('id',id);
  126. if(inputType === 'checkbox') {
  127. input.addClass('checkbox');
  128. }
  129. if(settings.singleSelect) {
  130. input.attr('name', 'ms'+multiSelectId+'-option');
  131. }
  132. var label=$('<label/>');
  133. label.attr('for', id);
  134. label.text(element.text() || item);
  135. label.attr('title', element.text() || item);
  136. if(settings.checked.indexOf(item) !== -1 || checked) {
  137. input.prop('checked', true);
  138. }
  139. if(checked){
  140. if(settings.singleSelect) {
  141. settings.checked = [item];
  142. settings.labels = [item];
  143. } else {
  144. settings.checked.push(item);
  145. settings.labels.push(item);
  146. }
  147. }
  148. input.change(function(){
  149. var value = $(this).attr('id').substring(String('ms'+multiSelectId+'-option').length+1);
  150. var label = $(this).next().text().trim();
  151. if($(this).is(':checked')) {
  152. if(settings.singleSelect) {
  153. settings.checked = [];
  154. settings.labels = [];
  155. $.each(self.find('option'), function() {
  156. $(this).removeAttr('selected');
  157. });
  158. }
  159. element.attr('selected','selected');
  160. if(typeof settings.oncheck === 'function') {
  161. if(settings.oncheck(value)===false) {
  162. $(this).prop('checked', false);
  163. return;
  164. }
  165. }
  166. settings.checked.push(value);
  167. settings.labels.push(label);
  168. $(this).parent().addClass('checked');
  169. } else {
  170. var index=settings.checked.indexOf(value);
  171. element.attr('selected',null);
  172. if(typeof settings.onuncheck === 'function') {
  173. if(settings.onuncheck(value)===false) {
  174. $(this).prop('checked',true);
  175. return;
  176. }
  177. }
  178. $(this).parent().removeClass('checked');
  179. settings.checked.splice(index,1);
  180. settings.labels.splice(index,1);
  181. }
  182. var oldWidth=button.width();
  183. button.children('span').first().text(settings.labels.length > 0
  184. ? settings.labels.join(', ')
  185. : settings.title);
  186. var newOuterWidth = Math.max(
  187. (button.outerWidth() - 2),
  188. settings.minOuterWidth
  189. ) + 'px';
  190. var newWidth=Math.max(button.width(),settings.minWidth);
  191. var pos=button.position();
  192. button.css('width',oldWidth);
  193. button.animate({'width':newWidth},undefined,undefined,function(){
  194. button.css('width','');
  195. });
  196. list.animate({'width':newOuterWidth,'left':pos.left});
  197. self.change();
  198. });
  199. var li=$('<li></li>');
  200. li.append(input).append(label);
  201. if(input.is(':checked')) {
  202. li.addClass('checked');
  203. }
  204. return li;
  205. }
  206. $.each(options,function(index,item){
  207. list.append(createItem(item));
  208. });
  209. button.parent().data('preventHide',false);
  210. if(settings.createText){
  211. var li=$('<li class="creator" title="' + settings.createText +
  212. '">+ ' + settings.createText + '</li>');
  213. li.click(function(event){
  214. li.empty();
  215. var input=$('<input type="text" class="new">');
  216. li.append(input);
  217. input.focus();
  218. input.css('width',button.innerWidth());
  219. button.parent().data('preventHide',true);
  220. input.keypress(function(event) {
  221. if(event.keyCode === 13) {
  222. event.preventDefault();
  223. event.stopPropagation();
  224. var value = $(this).val();
  225. var exists = false;
  226. $.each(options,function(index, item) {
  227. if ($(item).val() == value || $(item).text() == value) {
  228. exists = true;
  229. return false;
  230. }
  231. });
  232. if (exists) {
  233. return false;
  234. }
  235. var li=$(this).parent();
  236. var val = $(this).val();
  237. var select=button.parent().next();
  238. if(typeof settings.createCallback === 'function') {
  239. var response = settings.createCallback(select, val);
  240. if(response === false) {
  241. return false;
  242. } else if(typeof response !== 'undefined') {
  243. val = response;
  244. }
  245. }
  246. if(settings.singleSelect) {
  247. $.each(select.find('option:selected'), function() {
  248. $(this).removeAttr('selected');
  249. });
  250. }
  251. $(this).remove();
  252. li.text('+ '+settings.createText);
  253. li.before(createItem(this));
  254. var option=$('<option selected="selected"/>');
  255. option.text($(this).val()).val(val).attr('selected', 'selected');
  256. select.append(option);
  257. li.prev().children('input').prop('checked', true).trigger('change');
  258. button.parent().data('preventHide',false);
  259. button.children('span').first().text(settings.labels.length > 0
  260. ? settings.labels.join(', ')
  261. : settings.title);
  262. if(self.menuDirection === 'up') {
  263. var list = li.parent();
  264. list.css('top', list.position().top-li.outerHeight());
  265. }
  266. }
  267. });
  268. input.blur(function() {
  269. event.preventDefault();
  270. event.stopPropagation();
  271. $(this).remove();
  272. li.text('+ '+settings.createText);
  273. setTimeout(function(){
  274. button.parent().data('preventHide',false);
  275. },100);
  276. });
  277. });
  278. list.append(li);
  279. }
  280. var doSort = function(list, selector) {
  281. var rows = list.find('li'+selector).get();
  282. if(settings.sort) {
  283. rows.sort(function(a, b) {
  284. return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
  285. });
  286. }
  287. $.each(rows, function(index, row) {
  288. list.append(row);
  289. });
  290. };
  291. if(settings.sort && settings.selectedFirst) {
  292. doSort(list, '.checked');
  293. doSort(list, ':not(.checked)');
  294. } else if(settings.sort && !settings.selectedFirst) {
  295. doSort(list, '');
  296. }
  297. list.append(list.find('li.creator'));
  298. var pos=button.position();
  299. if(($(document).height() > (button.offset().top + button.outerHeight() + list.children().length * button.height()) &&
  300. $(document).height() - button.offset().top > (button.offset().top+button.outerHeight() + list.children().length * button.height())) ||
  301. $(document).height() / 2 > button.offset().top
  302. ) {
  303. list.css({
  304. top:pos.top+button.outerHeight()-5,
  305. left:pos.left,
  306. width:(button.outerWidth()-2)+'px',
  307. 'max-height':($(document).height()-(button.offset().top+button.outerHeight()+10))+'px'
  308. });
  309. list.addClass('down');
  310. button.addClass('down');
  311. list.slideDown(slideDuration);
  312. } else {
  313. list.css('max-height', $(document).height()-($(document).height()-(pos.top)+50)+'px');
  314. list.css({
  315. top:pos.top - list.height(),
  316. left:pos.left,
  317. width:(button.outerWidth()-2)+'px'
  318. });
  319. list.detach().insertBefore($(this));
  320. list.addClass('up');
  321. button.addClass('up');
  322. list.show();
  323. self.menuDirection = 'up';
  324. }
  325. list.click(function(event) {
  326. event.stopPropagation();
  327. });
  328. list.one('shut', closeDropDown);
  329. });
  330. $(window).click(closeDropDown);
  331. return span;
  332. };
  333. })( jQuery );