/** * jquery select2 sortable * - enable select2 to be sortable via normal select element * * author : vafour * inspired by : jquery chosen sortable (https://github.com/mrhenry/jquery-chosen-sortable) * license : gpl */ (function($){ $.fn.extend({ select2sortableorder: function(){ var $this = this.filter('[multiple]'); $this.each(function(){ var $select = $(this); // skip elements not select2-ed if(typeof($select.data('select2')) !== 'object'){ return false; } var $select2 = $select.siblings('.select2-container'), unselected = [], sorted; $select.find('option').each(function(){ !this.selected && unselected.push(this); }); sorted = $($select2.find('.select2-choices li[class!="select2-search-field"]').map( function() { if (!this) { return undefined; } var id = $(this).data('select2data').id; return $select.find('option[value="' + id + '"]')[0]; })); sorted.push.apply(sorted, unselected); $select.children().remove(); $select.append(sorted); }); return $this; }, select2sortable: function(){ var args = array.prototype.slice.call(arguments, 0); $this = this.filter('[multiple]'), validmethods = ['destroy']; if(args.length === 0 || typeof(args[0]) === 'object') { var defaultoptions = { bindorder : 'formsubmit', // or sortablestop sortableoptions : { placeholder : 'ui-state-highlight', items : 'li:not(.select2-search-field)', tolerance : 'pointer' } }; var options = $.extend(defaultoptions, args[0]); // init select2 only if not already initialized to prevent select2 configuration loss if(typeof($this.data('select2')) !== 'object'){ $this.select2(); } $this.each(function(){ var $select = $(this), $select2choices = $select.siblings('.select2-container').find('.select2-choices'); // init jquery ui sortable $select2choices.sortable(options.sortableoptions); switch(options.bindorder){ case 'sortablestop': // apply options ordering in sortstop event $select2choices.on("sortstop.select2sortable", function( event, ui ) { $select.select2sortableorder(); }); $select.on('change', function(e){ $(this).select2sortableorder(); }); break; default: // apply options ordering in form submit $select.closest('form').unbind('submit.select2sortable').on('submit.select2sortable', function(){ $select.select2sortableorder(); }); } }); } else if(typeof(args[0] === 'string')) { if($.inarray(args[0], validmethods) == -1) { throw "unknown method: " + args[0]; } if(args[0] === 'destroy') { $this.select2sortabledestroy(); } } return $this; }, select2sortabledestroy: function(){ var $this = this.filter('[multiple]'); $this.each(function(){ var $select = $(this), $select2choices = $select.parent().find('.select2-choices'); // unbind form submit event $select.closest('form').unbind('submit.select2sortable'); // unbind sortstop event $select2choices.unbind("sortstop.select2sortable"); // destroy select2sortable $select2choices.sortable('destroy'); }); return $this; } }); }(jquery));