禁用select2 clear上的下拉列表

似乎select2 4默认打开清除当前所选项目时的下拉列表。 以前的版本的select2似乎没有这种行为,我正在努力实现它,但现在没有运气。

有没有人知道如何挂钩清除事件所以我们可以禁用它的默认行为并清除所选的选项而不打开下拉列表?

干杯,Al

可以确认,防止事件似乎由于某种原因不起作用,所以你可以在一些超时后关闭下拉列表:

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

这是一个工作小提琴: http : //jsfiddle.net/obq3yLf2/

你不需要超时来完成这项工作,这是我的例子:

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

请在Github上查询相同内容。

防止select2:清除选择时打开

从那里我列出了提供的答案。

1选项

 $('#select-id').on('select2:unselecting', function() { var opts = $(this).data('select2').options; opts.set('disabled', true); setTimeout(function() { opts.set('disabled', false); }, 1); }); 

2选项

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

另一个简单实现:

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

取消选择其中一个项目后,我遇到了一个短暂延迟的问题,此解决方案为我解决了这个问题:

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