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
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.
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 .
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.
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(); } });
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With