Disable dropdown on select2 clear

Select2 4 seems to open a dropdown by default when clearing the currently selected item. Previous versions of select2 did not seem to have this behavior, and I'm trying to achieve it, but so far no luck.

Does anyone know how to connect to an explicit event so that we can disable its default behavior and clear the selected parameter without opening the drop-down list?

Cheers, Al

+6
source share
5 answers

You can confirm that for some reason, the warning does not seem to be triggering, so you can just close the drop-down list after some timeout:

$("select").select2({ allowClear: true }).on("select2:unselecting", function(e) { $(this).data('state', 'unselected'); }).on("select2:open", function(e) { if ($(this).data('state') === 'unselected') { $(this).removeData('state'); var self = $(this); setTimeout(function() { self.select2('close'); }, 1); } }); 

Here's a working fiddle: http://jsfiddle.net/obq3yLf2/

+9
source

You do not need a timeout to complete this work, here is my example:

 $('#my-select').select2({ allowClear: true }).on('select2:unselecting', function() { $(this).data('unselecting', true); }).on('select2:opening', function(e) { if ($(this).data('unselecting')) { $(this).removeData('unselecting'); e.preventDefault(); } }); 
+19
source

Please refer to Github for the same.

Prevent select2: open when cleaning selection

From there, I listed the answers provided.

1 option

 $('#select-id').on('select2:unselecting', function() { var opts = $(this).data('select2').options; opts.set('disabled', true); setTimeout(function() { opts.set('disabled', false); }, 1); }); 

Option 2

 var $el = $('#select-id'); $el.on('select2:unselecting', function(e) { $el.data('unselecting', true); }).on('select2:open', function(e) { // note the open event is important if ($el.data('unselecting')) { $el.removeData('unselecting'); // you need to unset this before close $el.select2('close'); } }); 
+1
source

Another simple implementation:

  $('select').on('select2:unselect', function(evt) { $(this).select2({ placeholder : { id : '', text : '---None Selected---' }, allowClear : true, theme : "bootstrap" }).select2('close'); }); 
0
source

I had a problem with a slight delay after deselecting one of the elements, and this solution fixed this problem for me:

 $(this).select2({ multiple: 'multiple', }).on("select2:unselecting", function(e) { var self = $(this); setTimeout(function() { self.select2('close'); }, 0); }); 
0
source

Source: https://habr.com/ru/post/985092/


All Articles