Disable dropdown opening on select2 clear

前端 未结 4 535
有刺的猬
有刺的猬 2021-02-04 01:16

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 a

相关标签:
4条回答
  • 2021-02-04 01:41

    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/

    0 讨论(0)
  • 2021-02-04 01:49

    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);
    });
    
    0 讨论(0)
  • 2021-02-04 01:50

    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();
        }
    });
    
    0 讨论(0)
  • 2021-02-04 01:56

    Another simple Implementation:

    $('select').on('select2:unselect', function(evt) {
        $(this).select2({
            placeholder : {
                id : '',
                text : '---None Selected---'
            },
            allowClear : true,
            theme : "bootstrap"
        }).select2('close');
    });
    
    0 讨论(0)
提交回复
热议问题