multiselect.js 11 KB

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