Search code examples
twitter-bootstrapjquery-select2-4

Jquery select2 plugin allowClear behavior


I'm trying to use the new version of select2 Plugin (4.0.2.rc1) but I have a problem with allowClear action.

$('select').select2({
   theme: 'bootstrap',
   placeholder: '..',
   allowClear: true
});

With the version 3.5.2 the "clear" action works well, but with this version when I click to x to clean the choice will clean the choice but even open the drop-down menu

enter image description here

How can I fix this issue? Thank you


Solution

  • For those interested this is the solution to the problem, hoping it will correct the problem in the new version of the plugin.

    $('select').select2({
       theme: 'bootstrap',
       placeholder: '..',
       allowClear: true
    });
    
    /* FIX */
    var $el = $('select');
    $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');
       }
    });