multiselect.js 11 KB

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