multiselect.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 = 200;
  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. button.click(function(event){
  77. var button=$(this);
  78. if(button.parent().children('ul').length>0) {
  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. });
  84. } else {
  85. button.parent().children('ul').fadeOut(slideDuration,function() {
  86. button.parent().children('ul').remove();
  87. button.removeClass('active up');
  88. });
  89. }
  90. return;
  91. }
  92. var lists=$('ul.multiselectoptions');
  93. lists.slideUp(slideDuration,function(){
  94. lists.remove();
  95. $('div.multiselect').removeClass('active');
  96. button.addClass('active');
  97. });
  98. button.addClass('active');
  99. event.stopPropagation();
  100. var options=$(this).parent().next().children();
  101. var list=$('<ul class="multiselectoptions"/>').hide().appendTo($(this).parent());
  102. var inputType = settings.singleSelect ? 'radio' : 'checkbox';
  103. function createItem(element, checked){
  104. element=$(element);
  105. var item=element.val();
  106. var id='ms'+multiSelectId+'-option-'+item;
  107. var input=$('<input type="' + inputType + '"/>');
  108. input.attr('id',id);
  109. if(inputType === 'checkbox') {
  110. input.addClass('checkbox');
  111. }
  112. if(settings.singleSelect) {
  113. input.attr('name', 'ms'+multiSelectId+'-option');
  114. }
  115. var label=$('<label/>');
  116. label.attr('for', id);
  117. label.text(element.text() || item);
  118. label.attr('title', element.text() || item);
  119. if(settings.checked.indexOf(item) !== -1 || checked) {
  120. input.prop('checked', true);
  121. }
  122. if(checked){
  123. if(settings.singleSelect) {
  124. settings.checked = [item];
  125. settings.labels = [item];
  126. } else {
  127. settings.checked.push(item);
  128. settings.labels.push(item);
  129. }
  130. }
  131. input.change(function(){
  132. var value = $(this).attr('id').substring(String('ms'+multiSelectId+'-option').length+1);
  133. var label = $(this).next().text().trim();
  134. if($(this).is(':checked')) {
  135. if(settings.singleSelect) {
  136. settings.checked = [];
  137. settings.labels = [];
  138. $.each(self.find('option'), function() {
  139. $(this).removeAttr('selected');
  140. });
  141. }
  142. element.attr('selected','selected');
  143. if(typeof settings.oncheck === 'function') {
  144. if(settings.oncheck(value)===false) {
  145. $(this).prop('checked', false);
  146. return;
  147. }
  148. }
  149. settings.checked.push(value);
  150. settings.labels.push(label);
  151. $(this).parent().addClass('checked');
  152. } else {
  153. var index=settings.checked.indexOf(value);
  154. element.attr('selected',null);
  155. if(typeof settings.onuncheck === 'function') {
  156. if(settings.onuncheck(value)===false) {
  157. $(this).prop('checked',true);
  158. return;
  159. }
  160. }
  161. $(this).parent().removeClass('checked');
  162. settings.checked.splice(index,1);
  163. settings.labels.splice(index,1);
  164. }
  165. var oldWidth=button.width();
  166. button.children('span').first().text(settings.labels.length > 0
  167. ? settings.labels.join(', ')
  168. : settings.title);
  169. var newOuterWidth = Math.max(
  170. (button.outerWidth() - 2),
  171. settings.minOuterWidth
  172. ) + 'px';
  173. var newWidth=Math.max(button.width(),settings.minWidth);
  174. var pos=button.position();
  175. button.css('width',oldWidth);
  176. button.animate({'width':newWidth},undefined,undefined,function(){
  177. button.css('width','');
  178. });
  179. list.animate({'width':newOuterWidth,'left':pos.left});
  180. self.change();
  181. });
  182. var li=$('<li></li>');
  183. li.append(input).append(label);
  184. if(input.is(':checked')) {
  185. li.addClass('checked');
  186. }
  187. return li;
  188. }
  189. $.each(options,function(index,item){
  190. list.append(createItem(item));
  191. });
  192. button.parent().data('preventHide',false);
  193. if(settings.createText){
  194. var li=$('<li class="creator" title="' + settings.createText +
  195. '">+ ' + settings.createText + '</li>');
  196. li.click(function(event){
  197. li.empty();
  198. var input=$('<input type="text" class="new">');
  199. li.append(input);
  200. input.focus();
  201. input.css('width',button.innerWidth());
  202. button.parent().data('preventHide',true);
  203. input.keypress(function(event) {
  204. if(event.keyCode === 13) {
  205. event.preventDefault();
  206. event.stopPropagation();
  207. var value = $(this).val();
  208. var exists = false;
  209. $.each(options,function(index, item) {
  210. if ($(item).val() == value || $(item).text() == value) {
  211. exists = true;
  212. return false;
  213. }
  214. });
  215. if (exists) {
  216. return false;
  217. }
  218. var li=$(this).parent();
  219. var val = $(this).val();
  220. var select=button.parent().next();
  221. if(typeof settings.createCallback === 'function') {
  222. var response = settings.createCallback(select, val);
  223. if(response === false) {
  224. return false;
  225. } else if(typeof response !== 'undefined') {
  226. val = response;
  227. }
  228. }
  229. if(settings.singleSelect) {
  230. $.each(select.find('option:selected'), function() {
  231. $(this).removeAttr('selected');
  232. });
  233. }
  234. $(this).remove();
  235. li.text('+ '+settings.createText);
  236. li.before(createItem(this));
  237. var option=$('<option selected="selected"/>');
  238. option.text($(this).val()).val(val).attr('selected', 'selected');
  239. select.append(option);
  240. li.prev().children('input').prop('checked', true).trigger('change');
  241. button.parent().data('preventHide',false);
  242. button.children('span').first().text(settings.labels.length > 0
  243. ? settings.labels.join(', ')
  244. : settings.title);
  245. if(self.menuDirection === 'up') {
  246. var list = li.parent();
  247. list.css('top', list.position().top-li.outerHeight());
  248. }
  249. }
  250. });
  251. input.blur(function() {
  252. event.preventDefault();
  253. event.stopPropagation();
  254. $(this).remove();
  255. li.text('+ '+settings.createText);
  256. setTimeout(function(){
  257. button.parent().data('preventHide',false);
  258. },100);
  259. });
  260. });
  261. list.append(li);
  262. }
  263. var doSort = function(list, selector) {
  264. var rows = list.find('li'+selector).get();
  265. if(settings.sort) {
  266. rows.sort(function(a, b) {
  267. return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
  268. });
  269. }
  270. $.each(rows, function(index, row) {
  271. list.append(row);
  272. });
  273. };
  274. if(settings.sort && settings.selectedFirst) {
  275. doSort(list, '.checked');
  276. doSort(list, ':not(.checked)');
  277. } else if(settings.sort && !settings.selectedFirst) {
  278. doSort(list, '');
  279. }
  280. list.append(list.find('li.creator'));
  281. var pos=button.position();
  282. if(($(document).height() > (button.offset().top + button.outerHeight() + list.children().length * button.height()) &&
  283. $(document).height() - button.offset().top > (button.offset().top+button.outerHeight() + list.children().length * button.height())) ||
  284. $(document).height() / 2 > button.offset().top
  285. ) {
  286. list.css({
  287. top:pos.top+button.outerHeight()-5,
  288. left:pos.left,
  289. width:(button.outerWidth()-2)+'px',
  290. 'max-height':($(document).height()-(button.offset().top+button.outerHeight()+10))+'px'
  291. });
  292. list.addClass('down');
  293. button.addClass('down');
  294. list.slideDown(slideDuration);
  295. } else {
  296. list.css('max-height', $(document).height()-($(document).height()-(pos.top)+50)+'px');
  297. list.css({
  298. top:pos.top - list.height(),
  299. left:pos.left,
  300. width:(button.outerWidth()-2)+'px'
  301. });
  302. list.detach().insertBefore($(this));
  303. list.addClass('up');
  304. button.addClass('up');
  305. list.fadeIn();
  306. self.menuDirection = 'up';
  307. }
  308. list.click(function(event) {
  309. event.stopPropagation();
  310. });
  311. });
  312. $(window).click(function() {
  313. if(!button.parent().data('preventHide')) {
  314. // How can I save the effect in a var?
  315. if(self.menuDirection === 'down') {
  316. button.parent().children('ul').slideUp(slideDuration,function() {
  317. button.parent().children('ul').remove();
  318. button.removeClass('active down');
  319. });
  320. } else {
  321. button.parent().children('ul').fadeOut(slideDuration,function() {
  322. button.parent().children('ul').remove();
  323. button.removeClass('active up');
  324. });
  325. }
  326. }
  327. });
  328. return span;
  329. };
  330. })( jQuery );