Skip to content

Instantly share code, notes, and snippets.

@sasknot
Created July 2, 2014 20:00
Show Gist options
  • Save sasknot/66ce5383e0de02d5984d to your computer and use it in GitHub Desktop.
Save sasknot/66ce5383e0de02d5984d to your computer and use it in GitHub Desktop.
Commom select2 types
(function($){
'use strict';
$.fn.applySelect2 = function() {
this.filter('.select2-no-search').each(function(){
var options = $(this).data('options') || {};
$.extend( options, { minimumResultsForSearch: -1 } );
$(this).data('options', options);
});
this.filter('.select2-tags').each(function() {
var options = $(this).data('options') || {};
$.extend( options, { tags: [] } );
$(this).data('options', options);
});
this.filter('.select2-unique-selection').each(function() {
$(this)
.addClass('select2-already-applied')
.select2({
allowClear: true
})
.on('select2-selecting', function( event ) {
var uniqueKey = $(this).find('option[value="' + event.val + '"]').data('unique-key');
$(this).find('option[data-unique="' + uniqueKey + '"]').not('option[value="' + event.val + '"]').attr('disabled', 'disabled');
})
.on('select2-removed', function( event ) {
var uniqueKey = $(this).find('option[value="' + event.val + '"]').data('unique-key');
$(this).find('option[data-unique="' + uniqueKey + '"]').removeAttr('disabled');
});
});
return this.each(function(){
if( $(this).hasClass('select2-already-applied') === false ) {
var thisOptions = $(this).data('options') || {};
var options = $.extend({
placeholder: true,
adaptContainerCssClass: function(){ return ''; },
containerCssClass: 'select2-custom',
dropdownCssClass: 'select2-custom'
}, thisOptions);
$(this).select2(options);
}
});
};
})(jQuery);
// Applying the select2, you can put this inside an ready/load event
$('select[class*="select2"], textarea[class*="select2"]').applySelect2();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment