multiselect.js 11 KB

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