Disable dropdown opening on select2 clear

依然范特西╮ 提交于 2019-12-04 10:32:12

问题


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


回答1:


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/




回答2:


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();
    }
});



回答3:


Please refer at Github for same.

Prevent select2:open when clearing selection

From there I have listed the provided answers.

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);
});

2 Option

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');
    }
});



回答4:


I had a problem with a short delay after deselecting one of the items and this solution fixed that issue for me:

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



回答5:


Another simple Implementation:

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


来源:https://stackoverflow.com/questions/29618382/disable-dropdown-opening-on-select2-clear

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!