Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable dropdown opening on select2 clear

Seems that select2 4 opens by default the dropdown when clearing the current selected item. Previous versions of select2 didn't seem to have that behaviour and I'm trying to achieve it but no luck for now.

Does anyone know how to hook into the clear event so we can disable it's default behaviour and clear the selected option without opening the dropdown?

Cheers, Al

like image 913
Alberto Avatar asked Apr 14 '15 02:04

Alberto


People also ask

How do I stop Select2 from auto selecting the first option?

This behaviour exists not because Select2 is forcing it, but because the browser is auto-selecting the first option for you. We can't control that, we can only work around it. Your best option is to use the placeholder support in Select2 and include a blank option tag as your default selection.

What triggers an event Choose 2?

Select2 will trigger a few different events when different actions are taken using the component, allowing you to add custom hooks and perform actions. You may also manually trigger these events on a Select2 control using . trigger .

How do I know if Select2 is open?

select2:open is fired whenever the dropdown is opened. select2:opening is fired before this and can be prevented. select2:close is fired whenever the dropdown is closed. select2:closing is fired before this and can be prevented.


2 Answers

You don't require a timeout to make this work, here's 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();     } }); 
like image 137
adamj Avatar answered Sep 21 '22 03:09

adamj


Can confirm, preventing events seems to not work for some reason, so you can just close the dropdown 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/

like image 20
Sam Arustamyan Avatar answered Sep 20 '22 03:09

Sam Arustamyan